# Version 2.0

The documentation for version 2.0 is under development. Please  expect changes and updates. We appreciate your understanding and patience as we work to provide comprehensive and accurate information.


# Using Conscent.ai

* To start creating content on Conscent.ai, you must follow the Authentication Guidelines. Conscent.ai will only allow authorized persons to create, view and edit content. The Client API Key and API Secret must be passed in Authorization Headers using Basic Authentication to use these APIs  (API Key as the username and API Secret as the password.

{% hint style="info" %}
Whenever you're utilizing the Web Integration Code or Calling any Conscent.ai APIs, you need to update the API\_URL and SDK\_URL variables based on your operating environment.
{% endhint %}

Conscent.ai provides two environments.&#x20;

#### SANDBOX ENVIRONMENT: TESTING/STAGING ENVIRONMENT&#x20;

|                                SDK\_URL                                |                        API\_URL                       |
| :--------------------------------------------------------------------: | :---------------------------------------------------: |
|  <p>\<a href="<https://conscent-sdk-v2-sandbox.netlify.app/csc-sdk.js> |                                                       |
| "><https://conscent-sdk-v2-sandbox.netlify.app/csc-sdk.js><br></a></p> | <p>\<a href="<https://sandbox-api.conscent.in/api/v2> |
|         "><https://sandbox-api.conscent.in/api/v2><br></a></p>         |                                                       |

#### PRODUCTION ENVIRONMENT: PRODUCTION ENVIRONMENT

|                 SDK\_URL                |             API\_URL             |
| :-------------------------------------: | :------------------------------: |
| <https://sdk-v2.conscent.in/csc-sdk.js> | <https://api.conscent.in/api/v2> |


# Web SDK

Integrating Conscent.ai on your Website is a simple and direct process. You start by copying the code below within the script tags - and adding it to the header section of your Route Index file.

<details>

<summary><mark style="color:orange;">Including this code in the header section allows the Conscent.ai Script to be initialized.</mark></summary>

{% code title="ConsCent Paywall Initalization Script:" %}

```
<script>
  const clientId = '5f92a62013332e0f667794dc';
  (function (w, d, s, o, f, cid) {
    if (!w[o]) {
      w[o] = function () {
        w[o].q.push(arguments);
      };
      w[o].q = [];
    }
    (js = d.createElement(s)), (fjs = d.getElementsByTagName(s)[0]);
    js.id = o;
    js.src = f;
    js.async = 1;
    js.title = cid;
    fjs.parentNode.insertBefore(js, fjs);
  })(window, document, 'script', '_csc', {SDK_URL}, clientId);
</script>
```

{% endcode %}

</details>

{% hint style="info" %}
Ensure you replace the 'clientId' with your actual Client ID retrieved from the [Conscent.ai Dashboard](https://stage-client.tsbdev.co/client/dashboard/Documentation) and the {SDK\_URL} with the [SDK URL](broken://pages/EPJH1OVqWR9bKMAfBFta) of an environment you want to use.
{% endhint %}

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following function on all the content/article pages.

<details>

<summary><mark style="color:orange;">Initialization of the Paywall</mark></summary>

```javascript
const csc = window._csc;
csc('show');
csc('init', {
 storyId: contentId,
 clientId: clientId,
 title: contentTitle,
 contentUrl: url,
 categories: ["category1", "category2,"category3"],
 tags: ["free", "premium", "metered"],
 sections: ["section1", "section2","section3"],
 authorName: "name",
 publicationDate: ISOstring,
 successCallback: yourSuccessCallbackFunction,
 wrappingElementId: 'paywalls-container',
})

```

</details>

We import the initialization script using the unique '\_csc' identifier and run the 'init' function by passing several parameters

<table><thead><tr><th width="225">Parameter</th><th width="319">Description</th><th>Default</th></tr></thead><tbody><tr><td><pre><code>storyId
</code></pre></td><td>The 'storyId' which should be identical to the Story ID by which the particular content is registered - in the Client CMS. This allows us to identify each piece of unique content for a client.</td><td>REQUIRED</td></tr><tr><td><pre><code>clientId
</code></pre></td><td>The 'clientId' is retrieved from the <a href="https://client.conscent.in/client/dashboard/Documentation">Client Integrations Page</a> of the ConsCent Client Dashboard.</td><td>REQUIRED</td></tr><tr><td><pre><code>title
</code></pre></td><td>The 'title' should be the Content Title by which the particular content is registered within the Client CMS.</td><td>REQUIRED</td></tr><tr><td><pre><code>wrappingElementId
</code></pre></td><td>'wrappingElementId' is the id of an element (e.g. a div with absolute positioning on your website) within which you want the paywall to be embedded. Your element should have a minimum width of 320 pixels and a minimum height of 550 pixels for the conscent.ai paywall to fit properly.</td><td>REQUIRED</td></tr><tr><td><pre><code>subscriptionUrl
</code></pre></td><td>The 'subscriptionUrl' is the link to the Subscription page of the client's website - in cases when a user would like to subscribe to the client's website for accessing the content offered.</td><td>OPTIONAL</td></tr></tbody></table>

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FLJ9nF8iK5V8Gpy6ZADm3%2FScreenshot%202023-06-05%20at%2012.06.07%20AM.png?alt=media&amp;token=b741f192-e5a7-4475-9aa5-0341926d5fd6" alt="" width="563"><figcaption><p>Paywall</p></figcaption></figure>

<details>

<summary><mark style="color:orange;">SuccessCallback Function</mark></summary>

```
async function yourSuccessCallbackFunction(validationObject: any) {
  // Function to show the premium content to the User since they have paid for it via ConsCent
  // Here you should verify the  validationObject with our backend
  // And then you must provide access to the user for the complete content

  // example verification code:
  console.log('Initiating verification with conscent backend');
  const xhttp = new XMLHttpRequest(); // using vanilla javascript to make a post request
  const url = `${API_URL}/content/consumption/${validationObject.consumptionId}`;
  xhttp.open('POST', url, true);
  // e is the response event
  xhttp.onload = (e) => {
    const backendConfirmationData = JSON.parse(e.target.response);

    // verifying that the validation received matches the backend data
    if (
      validationObject.consumptionId === backendConfirmationData.consumptionId &&
      validationObject.payload.clientId === backendConfirmationData.payload.clientId &&
      validationObject.payload.contentId === backendConfirmationData.payload.contentId
    ) {
      // Validation successful
      console.log('successful validation');
      // accessContent would be your function that will do all the actions that need to be done to unlock the entire content
      accessContent(true);
    }
  };
  xhttp.send();
}
```

</details>

You need to implement a 'successCallback' function which will receive a response containing a validationObject shown below - indicating whether the user has purchased the content, or if the user has access to the content already since they have purchased it before, or whether the transaction has failed and the user has not purchased the content.

```
{ "message": "Content Purchased Successfully", 
"payload": { 
 "clientId": "5fbb40b07dd98b0e89d90a25",
 "contentId": "Client Content Id 5",
 "createdAt": "2020-12-29T05:51:31.116Z" 
 }, 
 "consumptionId": "a0c433af-a413-49e1-9f40-ce1fbd63f568",
 "signature": "74h9xm2479m7x792nxx247998975393x08y9hubrufyfy3348oqpqqpyg78fhfurifr3" 
 }
```

|     validationObject Field     |                                             Meaning                                            |
| :----------------------------: | :--------------------------------------------------------------------------------------------: |
| Content Purchased Successfully |                         The user has purchased content via Conscent.ai.                        |
|         accessTimeLeft         | The user has purchased the content previously and still has free access to consume the content |
|          consumptionId         |      To verify each unique transaction by a user on the client's content with Conscent.ai      |

*<mark style="color:orange;">Please ensure that you call this function on all your content pages so that we can track all the events and provide accurate analytics.</mark>*


# Login

The ConsCent SSO service allows users to authenticate themselves on the ConsCent platform. This service supports both login and logout functionalities, which can be hosted by either ConsCent or client

### <mark style="color:orange;">**CONSCENT LOGIN:**</mark>&#x20;

The below code is used for implementing the ConsCent Login System.

#### User Login

To prompt the user to log in, use the following  code:

```javascript
const csc = window._csc as any;
csc('login-with-redirect',{useSocialLogin:boolean});
```

**Check User Authentication Status**

To check whether the user is logged in, use the following code:

```javascript
const csc = window._csc;
_csc('add-auth-state-listener', (userId) => {
  if (userId) {
    console.log('User is logged in');
  } else {
    console.log('User is not logged in');
  }
});

```

#### Fetch User Details

To retrieve the logged-in user's details, use the following code:

```javascript
const csc = window._csc;
csc('get-user-details', {
  successCallbackForUserDetails: async (userDetailsObject) => {
    console.log('Success callback received from ConsCent login', userDetailsObject);
  },
});
```

### <mark style="color:orange;">**CLIENT LOGIN:**</mark> &#x20;

The SSO service utilizes a **JWT (JSON Web Token)** authorization code, generated upon successful login, to manage user authentication. This guide outlines the necessary steps to integrate the SSO service into your application, including endpoint details and usage examples.

### Authorization Code (JWT)

Upon successful authentication, an authorization code in the form of a **JWT** is generated.

* **Signing Algorithm:** `RSA256`
* **Public Key Requirement:** To verify the JWT, share your **public key** with ConsCent in **PEM** (Privacy Enhanced Mail) format. The key must be **2048 bits**.

```
AuthorizationCodeToken {
  iss: string; // client group ID 
  sub: string; // user ID
  exp: number; // expiry date unix time
  iat: number; // issue date unix time
  jti: string; // session ID
  unq: string; // unique identifier for each authz_code (uuid v4 preferred)
  email?: string;
  phone?: string;
  name?: string;
}
```

#### **Login and Logout Endpoint**

* **URL:** The Login and Logout URLs need to be shared by the client with Conscent Team.
* **Functionality:**&#x20;

**For Login:** Redirects the user to the specified login page for authentication. Once authenticated, the service generates an authorization code and redirects the user to a URL specified in the `redirectUrl` query parameter.

**For Logout:** Redirects the user to the specified logout page, logs them out.The user is then redirected to a URL specified in the `redirectUrl` query parameter.

* **Required Parameters:**
  * **redirectUrl:** Specifies the URL where the user should be redirected post-login.
  * **clientId:** Specifies the client’s unique identifier.

**Example Requests:**

```javascript
*Login Request*

REDIRECT https://sso.host/login?redirectUrl=https://yourapp.com/home&clientId=client1

*Logout Request*

REDIRECT https://sso.host/logout?redirectUrl=https://yourapp.com/home&logoutFromAllDevices=false&clientId=client1

```

**Example Response:**

<pre class="language-javascript"><code class="lang-javascript">*After successful authentication, the user is redirected to*

REDIRECT https://yourapp.com/home?authorizationCode=AUTH_CODE

<strong>*After successful logout, the user is redirected to*
</strong>
REDIRECT https://yourapp.com/home

</code></pre>


# Logout

To log out the user, use the following code:

```javascript
Const csc=window._csc as any;
csc(‘logout’);
```


# User Details Drawer

The userDetailsPage function opens a drawer displaying user details after a successful login. This feature is available only if you're using Conscent's login system.

**Note:** This feature works only with Conscent's login system.

```javascript
const userDetailsPage = () => {
  console.log('User details page on its way.');
  // @ts-ignore
  const csc = window._csc as any;
  csc('open-user-details-page', {
    onSuccess: (data: any) => {
      console.log(data);
    },
  });
};

```

## Usage:

1. **Pre-requisite**: Ensure Conscent's login system is integrated.
2. **Trigger**: Call `userDetailsPage()` after login to open the drawer with user details.
3. **On Success**: User details will be available in the `data` object within the `onSuccess` callback.
4. Add a div defining the id to it. **for eg:** \<div id="users">\</div>

```javascript
document.getElementById('profile-icon').addEventListener('click', () => {
  userDetailsPage();
});
```


# Google One Tap

To enable Google One Tap login functionality within Conscent's client environment, follow the steps below:

**Initialization Process:** To initialize Google One Tap login, use the following parameters:

```javascript
csc('google-one-tap', {
    clientId,
    contentId: storyContent,
    successCallback: (data: {
	loggedIn:true,
        userId:string,
	email:string,
	name:string,
	phoneNumber:string}) 
		=> {
      console.log(data.loggedIn);
    },
    oneTapArgs: (data: argsObject) => {
      console.log(data);
    },
});
```

| Parameter       | Description                                                                                                                                    |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| clientId        | The unique identifier provided by Conscent for authenticating the client.                                                                      |
| contentId       | The ID of the content where the One Tap login is integrated.                                                                                   |
| successCallback | A callback function is triggered upon successful user login.                                                                                   |
| oneTapArgs      | A callback function returns information related to the One Tap process, including any errors or reasons for not displaying the One Tap prompt. |

**Parameters Overview**

The argsObject will return the following object type:

```javascript
argsObject = {
    getNotDisplayedReason: "browser_not_supported" || "Missing_client_id" || "Opt_out_or_no_session" || "Secure_http_required" || "Suppressed_by_user" || "Unregistered_origin" || "Unknown_reason",
    isDisplayed: true || false,
    isNotDisplayed: true || false,
    getSkippedReason: "auto_cancel" || "user_cancel" || "tap_outside" || "issuing_failed"
};
```

* **getNotDisplayedReason**: Provides reasons for not displaying the One Tap prompt. Choose from the available options.
* **isDisplayed**: Indicates whether the One Tap prompt is displayed.
* **isNotDisplayed**: Indicates whether the One Tap prompt is not displayed.
* **getSkippedReason**: Provides reasons for skipping the One Tap prompt.

#### URL Whitelisting on GCP

Ensure the following URLs are whitelisted according to the environment:

* **Sandbox**: `https://`sandbox-sso-v2.netlify.app`/`
* **Production**: `https://`slp-v2.netlify.app`/`


# Mobile SDK

A Mobile SDK is a software package that contains a set of tools that can help to build platform-specific mobile applications and implement new features in existing mobile apps.


# iOS(Swift)

This guide provides step-by-step instructions on how to include the Conscent.ai Plugin in your iOS app. The Conscent.ai Plugin is developed in swift Language.

**Pre-requisites**

&#x20;Conscent.ai iOS SDK supports **iOS 13.0** and above.

<details>

<summary>Installation Steps</summary>

You can download the CCPlugin.xcframework File from [<mark style="color:orange;">`here`</mark>](https://github.com/tsbmediaventure/ConsCent-docs/blob/master/docs/mobile/IOS%20V2%20SDK/CCPlugin.xcframework.zip) and add it to your project.

Make sure you change the embed mode for CCPlugin.xcframework to "**Embed & Sign**".

</details>

<details>

<summary>Initialize the SDK</summary>

1. Import the CCPlugin framework into your ViewController class.

```swift
import CCPlugin
```

2. Configure the SDK in didFinishLaunchingWithOptions in AppDelegate class

```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Configure the SDK
  CCPlugin.shared.configure(mode: .sandbox, clientID: "your-client-id")
  // ApplicationDelegate needs to be only called in case of Facebook Login
  ApplicationDelegate.shared.application(
                    application,
                    didFinishLaunchingWithOptions: launchOptions
                )
  // Additional configurations if necessary
  return true
}
```

* yourClientId - Pass your clientId received from Conscent.ai.
* Mode - configuration testing of different environments available.&#x20;

<pre class="language-swift"><code class="lang-swift"><strong>Api Mode can be set as :
</strong>   Mode.sandbox
   Mode.production
</code></pre>

3. You need to set the scrollDepth for the paywall by accessing the scrollDepth property of the CCPlugin.shared instance and modifying its value.

```swift
// Retrieve and set the scroll depth
let screenHeight = scrollView.bounds.height
let scrollDepth: Int = Int(scrollView.contentOffset.y)
CCplugin.shared.scrollDepth = scrollDepth
```

4. You have to confirm UIScrollViewDelegate and you need to set scrollDepth and scrollDepthPercentage.

```swift
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let scrollDepth: Int = Int(scrollView.contentOffset.y)
    CCplugin.shared.scrollDepth = scrollDepth
    let contentHeight = scrollView.contentSize.height
    let scrollViewHeight = scrollView.bounds.height
    let scrollOffset = scrollView.contentOffset.y
    // Calculate the scroll percentage
    let scrollDepthPercentage = (scrollOffset / (contentHeight - scrollViewHeight)) * 100.0
    // Use the scrollPercentage as needed (e.g., update a label or send to analytics)
    print("Scroll Depth: \(scrollDepthPercentage)%")
    CCplugin.shared.scrollDepthPercentage = scrollDepthPercentage
  }
  func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    let contentHeight = scrollView.contentSize.height
    let scrollViewHeight = scrollView.bounds.height
    let scrollOffset = scrollView.contentOffset.y
    // Calculate the scroll percentage
    let scrollDepthPercentage = (scrollOffset / (contentHeight - scrollViewHeight)) * 100.0
    // Use the scrollPercentage as needed (e.g., update a label or send to analytics)
    print("Scroll Depth: \(scrollDepthPercentage)%")
    CCplugin.shared.scrollDepth = Int(scrollOffset)
    CCplugin.shared.scrollDepthPercentage = scrollDepthPercentage
  }
```

5. You need to set the pageLength for the paywall by accessing the pageLength property of the CCPlugin.shared instance and modifying its value.

```swift
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    debugPrint("pageLength:\(scrollView.contentSize.height)")
    CCplugin.shared.pageLength = Int(scrollView.contentSize.height)
  }
```

Enabling the debug mode:

*The debugMode property of the CCPlugin.shared instance can be set to true or false to enable or disable debug mode. When debug mode is enabled, toasts will be shown if the content ID or client ID entered is incorrect. This is useful for development purposes.*

```swift
CCplugin.shared.debugMode = false
```

</details>

<details>

<summary>Initialize the paywall</summary>

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following method on all the content/article pages.

```swift
 CCplugin.shared.showPayWall(contentID: contentID,
                    variables: ["packageName":"cc.plugin.com", "device":"IOS"],
                    title: contentID,
                    categories: ["category1","category2","category3"] ,
                    sections: ["section12","section14"],
                    tags: ["premium"],
                    contentUrl: "https://www.google.com/",
                    authorName: "abc",
                    publicationDate: "2024-07-17T11:57:27.312Z",
                    parentView: view,
                    navigationController: self.navigationController,
                    eventParamsDelegate: self,
                    googleUserLogInDelegate: self,
                    completiondelegate: self,
                    signInDelegate: self
      )                                   
```

</details>

<details>

<summary>Google Login Process</summary>

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

```swift
pod 'GoogleSignIn'
```

2. 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](https://console.cloud.google.com/apis/credentials?project=_). For example: com.googleusercontent.apps.1234567890-abcdefg

```swift
<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>
```

3. To initiate a Google login

```swift
CCplugin.shared.configure(mode: .sandbox, clientID: clientID)
CCplugin.shared.googleUserLogIn(controller: self, googleUserLogInDelegate: self)
```

</details>

<details>

<summary>Facebook Login</summary>

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

```swift
pod 'FBSDKLoginKit', '17.4.0'
pod 'FBSDKShareKit', '17.4.0'
```

2. Update didFinishLaunchingWithOptions with the below code in Apthe pDelegate class.

```swift
 ApplicationDelegate.shared.application(
                    application,
                    didFinishLaunchingWithOptions: launchOptions
                )
```

3. To integrate Facebook Login into your iOS application, update your app's Info.plist file with the following entries. Replace the placeholders with the appropriate values from your Facebook app configuration.

Required Entries for Facebook Login

```swift
<key>FacebookAppID</key>
<string>YOUR_FACEBOOK_APP_ID</string>
<key>FacebookClientToken</key>
<string>YOUR_FACEBOOK_CLIENT_TOKEN</string>
<key>FacebookDisplayName</key>
<string>YOUR_FACEBOOK_APP_DISPLAY_NAME</string>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fbYOUR_FACEBOOK_APP_ID</string>
        </array>
    </dict>
</array>
```

</details>

| Parameters                    | Description                                                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| contentID (string)            | This will be your article or content id for which detail needs to be checked.                                                                                                                                                                                                                                                                                                                                      |
| parentView                    | Pass the view on which you are going to show your content.                                                                                                                                                                                                                                                                                                                                                         |
| completionDelegate            | This will be used to handle the success and failure cases. Pass the class as the delegate where you want to handle success or failure. This delegate is of the protocol CCPluginCompletionHandlerDelegate, which has three methods: purchasedOrNot(accessTime), success(accessType), onPaywallVisible(paywallType, paywallDisplayType, paywallHeight),loginSuccess(message, userId, authToken), `failure(message)` |
| subscriberDelegate(optional)  | <p>This is an optional callback that will be called if you pass your class as its delegate. It will be triggered when the subscription button is tapped. If you don't pass it in your delegate, it will not show the subscription view.</p><p>subscriberDelegate, which has one method: subscribeBtnTap() which will be triggered whenever the user clicks the Subscribe Button.</p>                               |
| signInDelegate(optional)      | <p>This is an optional callback that will be called if you pass your class as its delegate. It will be triggered when the sign-in button is tapped. If you don't pass it in your delegate, it will not show the sign-in view. </p><p>signInDelegate, which has one method: signInTap() that will be triggered when the user clicks the signin button.</p>                                                          |
| eventParamsDelegate(optional) | This will be used to get the events params. Pass the class as the delegate where you want to handle success. This delegate is of the protocol CCPluginEventParamsDelegate, which has methods: success(**paywallId**: String, **contentId**: String, **paywallType**: String, **clientId**: String, **anonId**: String) that will be triggered in case of google login click.                                       |
| googleLogInDelegate(optional) | This will be used to trigger your Google sign. This delegate is of the protocol CCPluginGoogleLogInDelegate, which has methods: startGoogleLogin() that will be triggered in case of google login click.                                                                                                                                                                                                           |

> **Mandatory Step**
>
> * In your Project go to your target and in the URL types add a new one with URL schemes "conscent".
> * This is important to handle redirection or app launches from the browser.
> * call below function inside of `openURLContexts` scene delegate(inbuilt in iOS).

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FZDyQNWH7JXjMGat4Vr7n%2FImage%2018-04-24%20at%202.43%E2%80%AFPM.jpg?alt=media&amp;token=21bda580-45d3-4478-90c9-4026b83a13e7" alt=""><figcaption><p>Atached a screenshot for the reference:</p></figcaption></figure>

```swift
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let url = URLContexts.first?.url {
       CCplugin.shared.handleRelaunchApp(url: url)
    }
}
```

> You need to call **CCplugin.shared.exitSDK()** while leaving the scope of current controller.

```swift
override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)
    if parent == nil {
      // Back button action was triggered
      debugPrint("Back button pressed")
      CCplugin.shared.exitSDK()
    }
  }
```

**Call the below function and pass the userId, after the user has logged in:**

```swift
CCplugin.shared.setClientUserId(clientUserId: "Your_User_Id")

```

<details>

<summary>Login Functionality</summary>

```swift
CCplugin.shared.configure(mode: .sandbox, clientID: clientID)
CCplugin.shared.userLogIn(userLogInDelegate: self)
```

**CCPluginUserLogInDelegate**

```swift
extension AccountViewController: CCPluginUserLogInDelegate {
  func userLogInSuccess(message: String, userId: String, authToken: String)
   {
    debugPrint("message: \(message), userId: \(userId), authToken: \(authToken)")
    }  
  func userLogInFailure(message: String, errorCode: String) {
        debugPrint(" message: \(message), errorCode: \(errorCode)")
        }
  func redirectToHomeScreen(message: String){
       debugPrint(" message: \(message)")
  }
}
```

</details>

**To enable Apple login follow either of 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. Go to [App Store Connect](https://appstoreconnect.apple.com/).
2. Select the app under "My Apps."
3. Go to "App Information."
4. Add "Sign in with Apple" information (privacy policy and terms of service URLs).
5. Enable "Sign in with Apple."
6. Submit changes for review.

<details>

<summary>Fetch User-details</summary>

```swift
CCplugin.shared.openUserDetails(userProfileDelegate: self)
CCplugin.shared.getUserDetail(completiondelegate: self)
```

**CCPluginUserDetailsDelegate**

```swift
extension AccountViewController: CCPluginUserDetailsDelegate {
    func success(userDetails: CCPlugin.UserDetails) 
    {
    debugPrint("PhoneNo.: \(userDetails.phoneNumber ?? "") Email: \(userDetails.email ?? "") Name: \(userDetails.name ?? "")")     
    }
    
    func failure(message: String, errorCode: String) 
    {
    debugPrint(" message: \(message), errorCode: \(errorCode)")
    }
    func userProfileUpdated(message: String, statusCode: String)
    {
    debugPrint("Message: \(message) statusCode:\(statusCode)")
    }
}
```

**CCPluginUserProfileDelegate:**

**Note: Use these messages to handle Logout in UserProfile Logout.**

USER\_LOGOUT\_SUCCESS&#x20;

USER\_LOGOUT\_FAILED&#x20;

USER\_DELETE\_ACCOUNT\_SUCCESS&#x20;

USER\_DELETE\_ACCOUNT\_FAILED

```swift
extension AccountViewController: CCPluginUserProfileDelegate{
    func success(message: String, statusCode: String) {
        debugPrint("Message: \(message) statusCode:\(statusCode)")
    }
    
    func failure(message: String, errorCode: String) {
        debugPrint("Message: \(message) errorCode:\(errorCode)")
    }
    
}
```

</details>

<details>

<summary>Custom Logout Functionality </summary>

**Custom Logout Functionality** refers to a logout process that is specifically designed and implemented based on a client’s requirements

**CCPluginUserLogOutDelegate:**

Pass the class as the delegate where you want to handle success or failure.&#x20;

This delegate is of the protocol CCPluginlogout, which has two methods:&#x20;

success() and failure() that will be triggered in case of success and failure of the process.

```swift
CCplugin.shared.userLogout(userLogOutDelegate: self)
```

```swift
extension AccountViewController: CCPluginlogout {
    func userLogOutSuccess() {
        debugPrint("loginSuccess")
    }
    
 func userLogOutFailure(message: String, errorCode: String) {
        debugPrint(" \(message), \(errorCode)")
        
    }
}
```

</details>

**To use only the Subscription Landing Page, call the below method:**

```
CCplugin.shared.openCustomUrl(customUrl: String)
```

> CustomUrl is URL of the Subscription Landing Page with clientId.

### Demo APP [<mark style="color:orange;">Link</mark>](https://github.com/conscent-ai/Demo-Blog-IOS)


# In-App Purchases with Conscent

This guide helps you integrate Apple In-App Purchases (IAP) with the Conscent Gateway.

It covers creating subscriptions in the App Store, retrieving credentials, configuring the Conscent Gateway, and setting up subscription plans. Follow these steps to go live with IAP smoothly.

<details>

<summary>Prerequisites</summary>

* An Apple Developer account with administrative access to App Store Connect.
* Your app is registered in App Store Connect with a unique Bundle ID.
* The latest Paid Applications Agreement is signed in the "Agreements, Tax, and Banking" section of App Store Connect.
* All required tax and banking information is fully completed in App Store Connect.

</details>

### **Step 1: Retrieve App Information from App Store Connect**

#### **1.1 Access App Store Connect**

* Navigate to [App Store Connect](https://appstoreconnect.apple.com/).
* Sign in with your Apple Developer credentials.

#### **1.2 Retrieve the Bundle ID and App Name**

* From the dashboard, click on **“My Apps”**.
* Select the app for which you want to configure In-App Purchases.
* To locate the **Bundle ID**:
  * In the sidebar, click on **“App Information”**.
  * Under **“General Information”**, find the **Bundle ID**.
* Note down both the **App Name** and the **Bundle ID** for future reference.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcH7o1CBDoGq23DGkDkW_5NfK_xUV_J3alFa4MaxOhT3k4ZswEh_umPcC3E9wNOymojAMRLikZj9Q5dKFvT-c0i7omr5LMvjvtzlyYpJAL1BXnZU_AoMh-yKFLVwky5uJtCep86PLhsB1CunRmgkwGa_1iG?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

### **Step 2: Obtain App Store Connect API Key and AuthKey File**

#### **2.1 Access Users and Access Section**

* In App Store Connect, click on **“Users and Access”** from the dashboard.

#### **2.2 Create a User with API Access**

* Click on the **”+”** icon to add a new user or select an existing one.
* Assign the user the **“Admin”** or **“App Manager”** role.
* Ensure the user has **API Access** enabled.

#### **2.3 Generate API Key for the User**

* Navigate to the **“Keys”** tab within **“Users and Access”**.
* Click on **“Generate API Key”**.
* Enter a name for the key and select **“Admin”** for access level.
* Click **“Generate”**.
* Download the **AuthKey\_\<KeyID>.p8** file and store it securely.
* Note down the following:
  * **Key ID**: Available in the **“Keys”** section.
  * **Issuer ID**: Found at the top of the **“Keys”** page.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdvoajR4WewspVPog8qU8R5RrPtS7hm9dmh6RgHtp7z5gn266dohrb-HcEuu_vn563PaaW45D7nQ1FOw8YECkyxdCTip3DBIuwOu_F5MPMa4hMBWdEj8KswQw85piGQTNvBZS1Bwq7x6myTfjxNrSFWGnE?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

* Click on **“Shared Secret”** and note it down as well.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fxjq6il2khMzyWFD8fZuV%2FShareSecret1.jpg.png?alt=media&amp;token=04d338f0-f70d-4d80-a423-4effa5838786" alt=""><figcaption></figcaption></figure>

### **Step 3: Configure the Conscent Gateway**

#### **3.1 Access Conscent Gateway Configuration**

* Log in to your **Conscent** dashboard.
* Navigate to the **“Monetize”** section.
* Click on **“Payment Gateway”** and select **“In-App Purchase Apple”**.

#### **3.2 Input App and Key Details**

* Enter the **App Name** and **Bundle ID** obtained earlier.
* Upload the **AuthKey.p8** file.
* Enter the **Key ID, Shared Secret Key,** and **Issuer ID** in their respective fields.

#### **3.3 Save Configuration**

* Review all the entered information for accuracy.
* Click on **“Save Changes”** to finalize the gateway configuration.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcf3mot0l63cVjr53_fbvX_PIet987gdiMJ-8QTru7h-avbxABRlXMyJtmNPPFl4WowZKnMhTe7bc46S-xsgR_bjRX6Ch7nA3TDhyQGxoONVuBFh6-_DtR_e8_f92qppz_57Ha-wtVIlus6y9HuFT_Mhsxy?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

### **Step 4: Create In-App Purchase Products in App Store Connect**

#### **4.1 Create a Subscription Group**

* In App Store Connect, select your app from **“My Apps”**.
* In the sidebar under **“Monetization”**, click on **“Subscriptions”**.
* If **“Subscriptions”** is not visible, ensure all agreements in **“Agreements, Tax, and Banking”** are accepted.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcAFlCL3DyJo1yubMwdS_TpveYot3aJ5qeh1wp-6obDLzI9Go281ZuFx1SuLBl44gZ8PxQIIDBPPOgBzwfojxOrUcctL5Q1Ov7RfzqF7YrxIfd0_yxyg4_dT1Jwqsma9NSngnIbdIjZBqG1rcvO0jOpYN_-?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

* Click on **“Create”** to add a new Subscription Group.
* Enter a **Reference Name** for internal use (e.g., “Premium Access Subscriptions”).
* Click **“Create”**.

#### **4.2 Add a Subscription Product**

* Within the Subscription Group, click on **“Create”** to add a new subscription.
* Enter the following:
  * **Reference Name**: Internal name for the subscription (e.g., “Premium Annual Subscription”).
  * **Product ID**: A unique identifier (e.g., “com.yourapp.premium.annual”).
  * **Recommendation**: Use a consistent naming convention.
  * Click **“Create”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fi2lgNzbcJu6P29d2UtNa%2Fimage%20(11).png?alt=media&amp;token=220aa7bd-7e56-4b03-8501-15d383a2a579" alt=""><figcaption></figcaption></figure>

#### **4.3 Set Subscription Duration and Price**

* Under **“Subscription Duration”**, select the appropriate duration (e.g., “1 Year”).
* Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F8GsaNWAoZII36ZZ8vUTS%2Fimage%20(12).png?alt=media&amp;token=5794c00f-9712-4fe7-91ec-7b1a18d4282c" alt=""><figcaption></figcaption></figure>

* In the **“Subscription Prices”** section, click **“Add Subscription Price”**.
* Choose a price tier from the dropdown menu.
* Click **“Next”** and confirm the prices for all regions.
* Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fe2xBJwnQqsbwEt3ZpiKG%2Fimage%20(13).png?alt=media&amp;token=3210727c-536f-404c-a37c-2c7b7915ff73" alt=""><figcaption></figcaption></figure>

#### **4.4 Add Localization Information**

* In the **“App Store Information”** section, click on the **”+”** icon next to **“Localization”**.
* Select the desired language (e.g., “English (U.S.)”).
* Enter the following:
  * **Subscription Display Name**: Visible to users (e.g., “Premium Annual Access”).
  * **Description**: Detail what the subscription offers.
  * Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FPAX9uWhW0AfFP26E0ok0%2Fimage%20(14).png?alt=media&amp;token=f4efb12a-8295-4ec5-8ea1-5a79e6c6d4dc" alt=""><figcaption></figcaption></figure>

#### **4.5 Add Reviewer Information**

* In the **“Review Information”** section, upload a screenshot of your subscription purchase screen.
* **Note**: The screenshot must meet Apple’s requirements.
* Optionally, add **Review Notes** to provide additional information to the reviewer.
* Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FIsaBwznGofNhqxR7cjU4%2Fimage%20(16).png?alt=media&amp;token=8cd585ea-8ed3-45ae-b5d9-33dd5c72e17a" alt=""><figcaption></figcaption></figure>

### **Step 5: Configure Subscription Plans in Conscent Dashboard**

#### **5.1 Access Subscription Plans**

* In the Conscent Dashboard, navigate to the **“Subscriptions”** section.
* Click on **“Create Subscription Plan”**.

#### **5.2 Choose Subscription Type**

* Select **“In-App”** as the subscription type.
* Choose between **“Recurring Subscription”** or **“One-Time Subscription”** based on your product.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F3PPMejNfcRDdQAqb7kvH%2Fimage%20(18).png?alt=media&amp;token=7fc2f67a-b555-47d7-ab76-e5219bee0184" alt=""><figcaption></figcaption></figure>

#### **5.3 Configure Recurring Subscriptions**

* **Subscription Group Name**: Enter the name of the Subscription Group created in App Store Connect.
* **Apple Product ID**: Enter the **Product ID** of the subscription.
* **Duration**: Specify the subscription duration (e.g., “1 Year”).

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FkFhlXvnHfZtqOApFBGBy%2Fimage%20(20).png?alt=media&amp;token=579fea1e-03a5-43ba-a374-ca067b9a1ec8" alt=""><figcaption></figcaption></figure>

#### **5.4 Configure Non-Renewing Subscriptions**

* **Apple Product ID**: Enter the **Product ID** of the non-renewing subscription.
* **Duration**: Specify the access duration (e.g., “6 Months”).
* **Price**: Leave blank; pricing will be determined by the price tier set in App Store Connect.

#### **5.5 Save Subscription Plan**

* Provide the other parameters and review the entered details.
* Click **“Save”** to create the subscription plan.

### **Step 6: Provide Starting Price CSV to Conscent**

#### **6.1 Download Pricing CSV from App Store Connect**

* In App Store Connect, navigate to your subscription product.
* Under **“Subscription Prices”**, click on **“Download”**.
* A **.zip** file containing the **.csv** pricing information will be downloaded.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FE6aQeK8c5PKQ1SEt7SXV%2Fimage%20(21).png?alt=media&amp;token=d5586555-c6ac-4993-a023-e8674e1c156a" alt=""><figcaption></figcaption></figure>

#### **6.2 Provide Pricing CSV to Conscent**

* Extract the **.csv** file from the downloaded **.zip**.
* Upload the **.csv** file to the Conscent Dashboard or provide it to your Conscent representative.
* This allows Conscent to synchronize pricing across different regions.

<details>

<summary><mark style="color:orange;background-color:blue;"><strong>I</strong><strong>NFORMATION THAT NEED TO SHARED WITH CONSCENT</strong></mark></summary>

* App Name
* Bundle ID
* KeyId
* AuthKey.p8 file
* Issuer Id
* One-Time Subscription Plan- ProductId + Duration
* Renewal Subscription Plan - Group Name + productId + Duration&#x20;
* CSV file of both the plans(StartingPrice and CurrentPrice)

</details>

### **Conclusion**

Your app is now ready to offer In-App Purchases to users, providing them with seamless access to your premium content. Should you require further assistance, please refer to Apple’s official documentation or contact Conscent team.

#### **Additional Resources**

* [Apple’s App Store Connect Help](https://help.apple.com/app-store-connect/)
* [In-App Purchase Programming Guide](https://developer.apple.com/in-app-purchase/)

**Note**: Always ensure compliance with Apple’s guidelines and review policies when setting up In-App Purchases to avoid any delays during the app review process.


# Android SDK

This is a step by step guide to include Conscent.ai Plugin in your app. This plugin is developed in Kotlin and supports both Java and Kotlin languages.

#### Pre-Requisites

Conscent.ai Android SDK supports **API 21 (Android 5.0)** and above. Please ensure the minSdkVersion is in the app's **build.gradle** file reflects the same.

{% hint style="info" %}
&#x20;*In case of an error for Kotlin not enabled - Enable Kotlin for Project.*

*In case of an error in Manifest merging - Merge Manifest as per Android Studio support or include the below line inside your application tag in the Android Manifest file.*

<pre class="language-xml" data-full-width="false"><code class="lang-xml"><strong>tools:replace="android:icon,android:roundIcon" 
</strong></code></pre>

{% endhint %}

{% hint style="info" %}
To integrate SDK, you need to enable the below-listed dependencies:

* Data Binding
* View Binding
* Jetpack Compose
  {% endhint %}

#### Permissions

Add the following permissions to the `AndroidManifest.xml` file.

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

<details>

<summary>Installation</summary>

You can download and add AAR File from [here](https://github.com/tsbmediaventure/ConsCent-docs/tree/master/docs/mobile/Android%20V2%20SDKs), which needs to be included in your **Module libs directory,** and tell gradle to install it like this:

```
Following files are required to be added.
```

```gradle
dependencies {
    implementation fileTree(include: [ '*.aar'], dir: 'libs')
}
```

</details>

<details>

<summary>Dependencies</summary>

In root level (project level) build.gradle, add classpath, and maven:

```gradle
dependencies {
    classpath 'com.google.gms:google-services:[latest-version]'
    // Add the Crashlytics Gradle plugin
    classpath 'com.google.firebase:firebase-crashlytics-gradle:[latest-version]'
}
```

In your application build.gradle file, include dependency as below with the latest versions:

```kotlin
dependencies{
// Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.9'
// Coroutines    
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
// Browser   
     implementation 'androidx.browser:browser:1.5.0'
     implementation 'com.google.android.gms:play-services-base:[latest-version]'
     implementation (platform("com.google.firebase:firebase-bom:[latest-version]"))
     implementation ("com.google.firebase:firebase-analytics-ktx")
     implementation ("com.google.firebase:firebase-crashlytics-ktx")
     implementation 'com.squareup.picasso:picasso:[latest-version]'
     implementation "androidx.swiperefreshlayout:swiperefreshlayout:[latest-version]"
     
// compose
def composeBom = platform('androidx.compose:compose-bom:2023.04.01')
implementation composeBom
androidTestImplementation composeBom

implementation "androidx.compose.material:material:1.4.3"
implementation 'androidx.compose.ui:ui'
// Android Studio Preview support
implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling'
// Optional - Integration with activities
implementation 'androidx.activity:activity-compose:1.7.2'
implementation 'androidx.constraintlayout:constraintlayout-compose:1.0.1'
implementation 'androidx.compose.ui:ui-text-google-fonts:1.5.0-beta02'

// Contains the core Credential Manager functionalities including password
// and passkey support.
implementation("androidx.credentials:credentials:1.3.0-alpha01")
// Provides support from Google Play services for Credential Manager,
// which lets you use the APIs on older devices.
implementation("androidx.credentials:credentials-play-services-auth:1.3.0-alpha01")
implementation("com.google.android.libraries.identity.googleid:googleid:1.1.0")
implementation ("com.google.firebase:firebase-auth-ktx:[latest-version]")
//fb dependency
implementation ("com.facebook.android:facebook-login:latest.release")
}
```

</details>

<details>

<summary>Initialize SDK</summary>

In your application or root activity class's method onCreate, pass these fields to be used in your app.

* applicationContext - Pass your application context.
* yourClientId - Pass your clientId received from Conscent.ai.
* yourAccentColor - Pass your accentColor for the app.
* Mode - configuration testing of different environments available. &#x20;
* APP\_MODE - used for checking the debug and production environment of the app.  &#x20;

```kotlin
Api Mode can be set as :
    ConscentConfiguration.MODE.SANDBOX
    ConscentConfiguration.MODE.PRODUCTION
```

&#x20;                                               &#x20;

```kotlin
APP_MODE can be set as : 
    ConsCentConfiguration.APP_MODE.DEBUG 
    ConsCentConfiguration.APP_MODE.PROD
```

*If APP\_MODE is DEBUG, all errors will be shown as Toast messages and Logs.*&#x20;

*If APP\_MODE is PROD, only logs will be available for critical errors like Network unavailability, wrong client\_id, and wrong content\_id.*

</details>

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
class TestingApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        ConscentWrapper.configure(
            application = this,
            clientId = "5f92a62013332e0f667794dc",
            appMode = ConscentConfiguration.APP_MODE.DEBUG,
            apiMode = ConscentConfiguration.MODE.SANDBOX,
        )
    }
}

```

{% hint style="info" %}
Pass the client ID received from Conscent.ai dashboard
{% endhint %}
{% endtab %}
{% endtabs %}

**Initialize the paywall**

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following method on all the content/article pages.

To have more control over the content flow, create an instance of the Conscent class inside your activity onCreate method for each unique contentId(recommended).

Use the below-described method:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
// Define a map with dynamic data
val variables: Map<String, String> = mapOf(
            "packageName" to "com.conscent.plugin",
            "device" to "ANDROID",
            "versionCode" to "20.4.5",)

val instance = ConscentWrapper.getConscentInstance(
            callingActivity = yourCallingActivity,
            parentView = yourParentView,
            containerView = yourContainerView,
            popUpContainer = yourPopUpContainerView,
            onConscentListener = onConscentListener,
            contentId = contentId,
            title = contentTitle,
            categories= arrayListOf("categorie1","categorie2","categorie3"),
            sections = arrayListOf("section","section1","section3"),
            tags = arrayListOf("premium"),
            url = ContentUrl,
            authorName = authorName,
            publicationDate = "2024-07-17T11:57:27.312Z",
            variables = variables //OPTIONAL
        )
//To display the registration paywall 
RegistrationPaywall.initRegistrationPaywall()
//To display the paywall       
Paywall.initRegularPaywall()
//To display the metered banner
MeterBanner.initMeterBanner()
```

{% endtab %}
{% endtabs %}

> #### Note: Include the AAR files of respective paywalls and banners before calling above functions.

#### To set the scroll depth on the content page:

```kotlin
instance.scrollDepth = scrollY
```

In case of Fragment, call the below method inside onDestoyView()-

```
instance.onDestroy()
```

<table><thead><tr><th width="294.5">Parameters</th><th>Description</th></tr></thead><tbody><tr><td>yourCallingActivity(Activity)</td><td>This is your activity content which is calling the methods and where callback will be received.</td></tr><tr><td>yourParentView(ConstraintLayout)</td><td>This will be the parent of your layout. Please keep ConstraintLayout as your root view in your activity xml file. Pass the reference of your root view in checkContent function.  </td></tr><tr><td>yourContainerView(FrameLayout)</td><td><p>This will be a FrameLayout where the payment page will be inflated. Create a frameLayout in your XML and pass it here as a reference.</p><p>For eg:</p><pre class="language-xml"><code class="lang-xml">&#x3C;FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</code></pre></td></tr><tr><td>contentId (String)</td><td>This will be your article or content id for which detail needs to be checked.</td></tr><tr><td>yourContentTitle (<code>String</code> - Optional)</td><td>Title of the content for display purposes.</td></tr><tr><td>yourSubsUrl (<code>String</code> - Optional)</td><td>Url is to be used when subscribe button is clicked.</td></tr><tr><td>canSubscribe (<code>Boolean</code> - Optional)</td><td>Pass this as "true" to show subscribe layout else as "false".</td></tr><tr><td>showClose (<code>Boolean</code> - Optional)</td><td>Pass this as "true" to show the close button on the paywall/subscriptions, the default value is <code>"false"</code></td></tr><tr><td>OnConscentListener</td><td>You can pass a listener which will get called after success or failure in processing. If you pass a listener, after successful processing, the success reference will be called and for a failed event, the failure event will be called</td></tr></tbody></table>

You can implement OnConscentListener in your activity and then pass it as a reference.

| Methods                | Description                                                                                                                                                                                                                                                                                        |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| onSuccess              | This is the success callback that will get called for every successful processing. You can pass your method as a reference or a lambda expression which will get called in case of success. This will send params clientId ,contentId , userId , authToken , accessType(PVM, SUBS, PASS, CONTENT). |
| onError (optional)     | You can pass it as null. This is the failure callback which will get called for every failed processing. You can pass your method as a reference or a lambda expression and it'll get called for failed cases. You can implement your code in it for failed cases.                                 |
| onSubscribe (optional) | If you want to inflate subscribe layout, pass a subscribe function which will be called when subscribe button will be clicked inside the payment flow. Passing null will not inflate subscribe layout.                                                                                             |
| onBuyPass (optional)   | It will be called when the buy-pass button will be clicked inside the payment flow.                                                                                                                                                                                                                |
| onSignIn               | This is the callback function that will be called when a user clicks on signIn button in the payment flow. This will be only visible if subscribe layout has been inflated.                                                                                                                        |
| onAdFree               | This is the callback function which will be called when a user clicks on adfree subscription.                                                                                                                                                                                                      |
| eventParams            | This callback function will be called when a user clicks on the Google login. This will send params paywallId,contentId, paywallType, clientId, and anonId.                                                                                                                                        |
| onShowPaywall          | This callback function will be called when a paywall is visible on the screen. This will send params - eventLocation, eventType, paywallDisplayType, paywallType.                                                                                                                                  |
| onGoogleLoginClick     | This will be used to trigger your Google sign. This callback function will be called when a user clicks on the Google login.                                                                                                                                                                       |
| onLoginSuccess         | This callback function will be called when a User LoggedIn successFuly. The message, userId, authToken will be received here.                                                                                                                                                                      |

#### To check if an article/content is free/paid or payment needs to be done, in your class, use as below sample: Parameters detail can be checked below for more information.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
instance.checkContentAccess(
     contentId
    )
```

{% endtab %}
{% endtabs %}

> Call <mark style="color:orange;">**checkContentAccess**</mark> method on override <mark style="color:orange;">**onNewIntent**</mark> method in Activity Class.

**Call the below function and pass the userId, after the user has logged in:**

```kotlin
PluginPreferences.setClientUserId("Your_User_Id")
```

<details>

<summary>Login Functionality</summary>

Call this method to invoke our Login System

```kotlin
ConscentWrapper.INSTANCE?.onSSOLogin(
        consCentLoginCallbacks = object : ConsCentLoginCallbacks {
         override fun onLoginSuccess(
         message: String,
                    userId: String,
                    authToken: String
                    ) {
            Log.d(TAG, " $message, $userId, $authToken ")
                    }

        override fun onLoginFailure(message: String, errorCode: String) {
            Log.d(TAG, "$message, $errorCode ")
                    }

                },
      override fun onRedirectToHomeScreen(message: String, errorCode: String) {
                        Log.d(
                            TAG,
                            "onRedirectToHomeScreen $message,"
                        )
                    }
        clientActivity = this@yourCallingActivity,
            )
```

</details>

<details>

<summary>Fetch User-details Method</summary>

**Call this method to show User Profile Page:**

```kotlin
ConscentWrapper.INSTANCE?.openUserDetails(
    clientActivity = this@yourCallingActivity,
    consCentUserProfileCallbacks = object: ConsCentUserProfileCallbacks {
        override fun userLogoutSuccess(message: String, statusCode: String) {
            Log.d(
                TAG,
                "$message $statusCode"
            )
        }

        override fun userLogoutFailed(message: String, statusCode: String) {
            Log.e(
                TAG,
                "$message $statusCode"
            )
        }

        override fun userDeleteAccountSuccess(message: String, statusCode: String) {
            Log.d(
                TAG,
                "$message $statusCode"
            )
        }

        override fun userDeleteAccountFailed(message: String, statusCode: String) {
            Log.e(
                TAG,
                 "$message $statusCode"
            )
        }

        override fun userNotLoggedIn(message: String, statusCode: String) {
            Log.e(
                TAG,
                "$message $statusCode"
            )
        }
        
       override fun userProfileUpdate(message: String, statusCode: String) {
                        Log.d(
                            TAG,
                            "consCentUserProfileCallbacks $message"
                        )
                    } 

    }
)
```

**Call this method to fetch user-details:**

```kotlin
ConscentWrapper.INSTANCE?.getUserDetails(
userDetailSuccess = { userDetails->
Log.d(TAG, "showUserDetails: $userDetails")
},
failure = {
Log.e(TAG, "showUserDetails: $it")
})
```

</details>

#### Logout the User:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
ConscentWrapper.INSTANCE?.onSSOLogOut(
                this@yourCallingActivity,
                consCentLogoutCallbacks = object : ConsCentLogoutCallbacks {
                    override fun onLogOutSuccess(message: String, successCode: String) {
                        Log.d(TAG, "$message  $successCode")
                    }

                    override fun onLogOutFailure(message: String, errorCode: String) {
                        Log.e(TAG, "$message  $errorCode")
                    }

                },
            )
```

{% endtab %}
{% endtabs %}

**To use only the Subscription Landing Page, call the below method:**

```
ConscentWrapper.INSTANCE?.openCustomUrl(context: Activity, customUrl: String)
```

> CustomUrl is URL of the Subscription Landing Page with clientId.

**Demo App:** [**Link**](https://github.com/RoshanSharma8245/Demo-Blog)


# 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**

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

```javascript
run pod install
```

<details>

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

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

```javascript
//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>

    );
};
```

</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                                                                         |
| ApiEnv                         | <p>ApiEnv can be set as : </p><p><code>SANDBOX</code> </p><p><code>LIVE</code></p>                    |
| currentStackName = {'Content'} | This key-value pair accepts a string value and redirects to the specified URL provided by the client. |

### Initialize the paywall

**Define these states on the content screen**

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

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

```javascript
//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 >
    )
```

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

<details>

<summary>EventListeners for Paywall, Login, Logout and userProfile</summary>

Implement the EventRegister method in your component:

* **USER\_NOT\_LOGIN:** Triggered when the user is not logged in.
* &#x20;**LOGIN\_SUCCESS**: Triggered when the user successfully logs in to the Conscent system.&#x20;
* **LOGIN\_FAILED:** Triggered when the user’s login attempt fails in the Conscent system.&#x20;
* **LOGOUT\_SUCCESS:** Triggered when the user logs out successfully.&#x20;
* **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.&#x20;
* **UNLOCK:** Unlocks the content and hides the paywall.&#x20;
* **JOURNEY\_FAILURE:** Handles errors while displaying the paywall.&#x20;
* **SUBS\_SUCCESS**: Handles successful subscription.&#x20;
* **PAYMENT\_SUCCESS:** Handles successful subscription payment.&#x20;
* **RZP\_CROSS\_BTN\_CLICKED:** Triggered when the Razorpay cross button is clicked.&#x20;
* **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.

```javascript
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);
      }
    };
  });
```

</details>

<details>

<summary>Login/Logout Functionality</summary>

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

```javascript
await login('Your_current_stack_name', props.navigation)

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

#### **Google Login Process (Android)**

Share the Google ClientID&#x20;

#### **Google Login Process (iOS)**&#x20;

Share the Google ClientID&#x20;

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

```xml
run pod install
```

2. 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](https://console.cloud.google.com/apis/credentials?project=_). For example: com.googleusercontent.apps.1234567890-abcdefg

```xml
<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>
```

</details>

<details>

<summary>Facebook Login </summary>

1. **Install the library**

using either Yarn:

```javascript
yarn add react-native-fbsdk-next
```

or npm:

```javascript
npm install --save react-native-fbsdk-next
```

2. **Link**

React Native 0.60+

[CLI autolink feature](https://github.com/react-native-community/cli/blob/main/docs/autolinking.md) links the module while building the app.

Note For iOS using cocoapods, run:

```bash
$ cd ios/ && pod install
```

React Native <= 0.59&#x20;

Note: For support with React Native <= 0.59, please refer to [React Native FBSDK](https://github.com/facebookarchive/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:&#x20;

\
Either follow the [instructions in the React Native documentation](https://facebook.github.io/react-native/docs/linking-libraries-ios#manual-linking) to manually link the framework or link using [Cocoapods](https://cocoapods.org/) by adding this to your `Podfile`:

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

Manually link the library on Android&#x20;

Make the following changes:

android/settings.gradle&#x20;

```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&#x20;

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

android/app/src/main/.../MainApplication.java&#x20;

On top, where imports are:

```kotlin
import com.facebook.reactnative.androidsdk.FBSDKPackage; 
```

Add the FBSDKPackage class to your list of exported packages.

```kotlin
@Override 
protected List 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](https://developers.facebook.com/docs/android/getting-started/) 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](https://developers.facebook.com/docs/ios/use-cocoapods) 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

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

Step 2: Inside didFinishLaunchingWithOptions, add the following:&#x20;

```objectivec
[[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:

```objectivec
- (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)](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<br>

**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.

```objectivec
#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**](https://github.com/facebook/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:

```objectivec
$(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`):

```objectivec
  # 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.

5. `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](https://github.com/thebergamo/react-native-fbsdk-next/issues/104#issuecomment-931488609)<br>

6. 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:

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

7. 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.<br>
8. 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](https://developers.facebook.com/docs/facebook-login/android#6--provide-the-development-and-release-key-hashes-for-your-app) 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](https://play.google.com/console/) and run this command:

```bash
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](https://developers.facebook.com/docs/facebook-login/android#6--provide-the-development-and-release-key-hashes-for-your-app) and enter them under **Key Hashes**.

9. 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

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

In android/app/src/main/java/com/csc\_demo/MainApplication.kt

```gradle
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

```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

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

```

android/build.gradle

```gradle
facebookSdkVersion = "13.1.0"
```

</details>

**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. Go to [App Store Connect](https://appstoreconnect.apple.com/).
2. Select the app under "My Apps."
3. Go to "App Information."
4. Add "Sign in with Apple" information (privacy policy and terms of service URLs).
5. Enable "Sign in with Apple."
6. Submit changes for review.

<details>

<summary>UserProfile Functionality</summary>

```javascript
await openUserProfile('Your_current_stack_name', props.navigation, '')
```

</details>

**DEMO APP** [**Link**](https://github.com/conscent-ai/csc-react-native-demo)


# Google In-App Purchases with Conscent

To enable the Google Play Android Developer API and the Google Play Developer Reporting API for your Google Cloud project, follow the steps outlined below:

<mark style="color:orange;">**Step 1. Enable the Google Developer and Reporting API**</mark>

1. **Access the Google API Console:** Open your browser and go to the Google API Console.
2. **Select Your Project:** Choose an existing project or create a new one.
3. **Enable the Required APIs:**
   1. Navigate to **Library** within the API Console.
   2. Search for and select the following APIs:
      1. **Google Play Android Developer API**
      2. **Google Play Developer Reporting API**
   3. Click **Enable** for each API.

**Note**: If the API is already enabled, you will see a **Manage** button instead.

4. **Set Up Credentials:**
   1. Once the APIs are enabled, you’ll be redirected to the API’s main page.
   2. If no credentials are set up, follow these steps to create them:
      1. Click on **Create Credentials**.
      2. Follow the on-screen prompts to generate the necessary credentials (OAuth 2.0, API keys, or service accounts) based on your project needs.
      3. Ensure that these credentials are created by the project owner or a user with the appropriate permissions.

**Important**: User permissions are defined in Step 3 of the Google Play Console and are required to access the Developer and Reporting APIs.

5. **Verify Permissions in Google Play Console:**
   1. Go to your **Google Play Console** and ensure the project owner or authorized user has the necessary permissions under **Settings > Permissions**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FCJM7lBYhrtxuOmSm4JnT%2F281139973-97660d3a-b963-4b1e-8be0-d5bc28080b33%20(1).gif?alt=media&amp;token=eb924906-2302-423c-9252-ede7c96c1f8b" alt=""><figcaption></figcaption></figure>

<mark style="color:orange;">**Step 2. Create a Service Account**</mark>

1. **Navigate to Service Accounts**
   1. Open the Google Cloud Console.
   2. Go to **IAM & Admin** > **Service Accounts**.
   3. Alternatively, if you're in the Google Play Console, you can reach this page from the last setup screen.
2. **Create the Service Account**
   1. Click **Create Service Account**.
   2. Enter a name for the service account (e.g., "Platform Server Notifications Service").
   3. Click **Create and continue**.
3. **Assign Roles to the Service Account**
   1. In the **Grant this service account access to the project** section, add the following roles:
      1. **Pub/Sub Admin**: Enables the account to manage Platform Server Notifications.
      2. **Monitoring Viewer**: Allows monitoring of the notification queue.
   2. **Tip**: If you can’t find these roles via search, manually browse for them under the **Pub/Sub** and **Monitoring** folders.
4. **Download the JSON Key**
   1. Once the roles are assigned, navigate to the **Service Accounts** page in the Google Cloud Console.
   2. In the **Actions** menu (three dots) for the new service account, select **Manage Keys**.
   3. Click **Add Key** > **Create new key**.
   4. Choose the **JSON** format and download the JSON key.
   5. **Important**: Keep this JSON key secure, as it will be required in **Step 4** of the setup process.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FjZhz0jz5JfePb9rOte4s%2F7706775-Crede_Step2aaaa_1294f8cec28bcec881ddd3946290d2b7-cec9dd14bc74a4e1c214161f01a332c6.gif?alt=media&amp;token=b42b37ab-1587-4a0d-8a94-e47ee5973d7c" alt=""><figcaption></figcaption></figure>

<mark style="color:orange;">**Step 3. Grant Financial Access**</mark>

1. **Access Users and Permissions**
   1. In the Google Play Console, navigate to the **Developer homepage**.
   2. Go to **Users and Permissions**.
2. **Invite the Service Account**
   1. Click on **Invite user**.
   2. Enter the email address of the service account created in Step 2.
3. **Set Permissions**
   1. Under **App permissions**, select your app to grant permissions specific to it.
   2. Under **Account permissions**, enable the following permissions:
      1. **View app information and download bulk reports (read-only)**: Allows access to view app details and download bulk data reports.
      2. **View financial data, orders, and cancellation survey responses**: Grants access to financial data and customer feedback.
      3. **Manage orders and subscriptions**: Allows management of customer orders and subscriptions.

* **Note**: Other permissions can be set based on your needs, but the three permissions listed above are essential for financial access.

4. **Send the Invitation**
   1. Scroll to the bottom and click **Invite user** to activate the service account under **Users and Permissions**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Far0DitFYkj654eFVc607%2F281139142-1bebe299-60db-4001-9329-0250324edb12.gif?alt=media&amp;token=578c7332-d44a-4d0d-be32-f1c900b22cf5" alt=""><figcaption></figcaption></figure>

<mark style="color:orange;">**Step 4. Share Credentials JSON and Package Name**</mark>

**Package Name**

Provide the unique package name for your application (e.g., `com.example.app`).

**JSON Key**

To integrate with Google Cloud, you must share the JSON Key from **Step 2** with the Customer Success or Product Team securely.

**Push Notification Configuration**

During Google Cloud Console configuration, push notifications must be set up to work with Conscent.

* Set up push notifications with the URL provided by Conscent and the Play Console.
* Follow the detailed guide here for push notification configuration: [Simplifying Google Play Console Cloud Project Setup](https://valueoutput.com/blogs/simplifying-google-play-console-cloud-project-setup-for-inapp-purchases/8zmvEBB5bwLWa7AmORhl)

**Subscription Plans Configuration (Conscent Dashboard)**

Please provide the following details for each subscription plan you wish to configure:

| Required Details        | Description                                                                                          |
| ----------------------- | ---------------------------------------------------------------------------------------------------- |
| Subscription Product ID | Unique identifier for the subscription plan (e.g., <mark style="color:purple;">sub\_monthly</mark>). |
| Base Plan ID            | Base plan identifier (e.g., <mark style="color:purple;">base\_plan\_123</mark>).                     |

**User Purchase Information:**

To complete the user purchase tracking, provide the following details:

<table><thead><tr><th width="279">Required Details	</th><th>Description</th></tr></thead><tbody><tr><td>User Purchase Country</td><td>The country of the user making the purchase (e.g., IN, US).</td></tr><tr><td>Base Plan ID</td><td>Base plan identifier associated with the purchase (e.g., <mark style="color:purple;">base_plan_123</mark>).</td></tr><tr><td>Subscription Product ID</td><td>Unique product identifier for the purchased item (e.g., <mark style="color:purple;">prod_456</mark>).</td></tr><tr><td>Purchase Token</td><td>Purchase token generated after the user completes a purchase (e.g., <mark style="color:purple;">purchase_token_xyz123)</mark>.</td></tr></tbody></table>

**Example Purchase Details:**

```json
{
  "orderId": "GPA.3311-5236-4464-24316",
  "packageName": "com.csc_demo",
  "productId": "conscent_product_id_1_m",
  "purchaseTime": "1738058807395",
  "purchaseState": 0,
  "purchaseToken": "ajibimdaeaiadogkflhpeggn.AO-J1OzRSKQF3Xyr4BHuN3Mxqe7YQwCqZwjB1G_Mi5IiIEL6hH64bAC1ak7TO4SGbh3zu5dOJkiUAx2Gc_-83xcLpHQrV-s9mw",
  "quantity": 1,
  "autoRenewing": true,
  "acknowledged": false
}

```

**Note**: Add the Conscent webhook URL to the Google account.[​](https://www.revenuecat.com/docs/service-credentials/creating-play-service-credentials#2-create-a-service-account)


# Apple In-App Purchases with Conscent

This guide helps you integrate Apple In-App Purchases (IAP) with the Conscent Gateway.

It covers creating subscriptions in the App Store, retrieving credentials, configuring the Conscent Gateway, and setting up subscription plans. Follow these steps to go live with IAP smoothly.

<details>

<summary>Prerequisites</summary>

* An Apple Developer account with administrative access to App Store Connect.
* Your app is registered in App Store Connect with a unique Bundle ID.
* The latest Paid Applications Agreement is signed in the "Agreements, Tax, and Banking" section of App Store Connect.
* All required tax and banking information is fully completed in App Store Connect.

</details>

### **Step 1: Retrieve App Information from App Store Connect**

#### **1.1 Access App Store Connect**

* Navigate to [App Store Connect](https://appstoreconnect.apple.com/).
* Sign in with your Apple Developer credentials.

#### **1.2 Retrieve the Bundle ID and App Name**

* From the dashboard, click on **“My Apps”**.
* Select the app for which you want to configure In-App Purchases.
* To locate the **Bundle ID**:
  * In the sidebar, click on **“App Information”**.
  * Under **“General Information”**, find the **Bundle ID**.
* Note down both the **App Name** and the **Bundle ID** for future reference.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcH7o1CBDoGq23DGkDkW_5NfK_xUV_J3alFa4MaxOhT3k4ZswEh_umPcC3E9wNOymojAMRLikZj9Q5dKFvT-c0i7omr5LMvjvtzlyYpJAL1BXnZU_AoMh-yKFLVwky5uJtCep86PLhsB1CunRmgkwGa_1iG?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

### **Step 2: Obtain App Store Connect API Key and AuthKey File**

#### **2.1 Access Users and Access Section**

* In App Store Connect, click on **“Users and Access”** from the dashboard.

#### **2.2 Create a User with API Access**

* Click on the **”+”** icon to add a new user or select an existing one.
* Assign the user the **“Admin”** or **“App Manager”** role.
* Ensure the user has **API Access** enabled.

#### **2.3 Generate API Key for the User**

* Navigate to the **“Keys”** tab within **“Users and Access”**.
* Click on **“Generate API Key”**.
* Enter a name for the key and select **“Admin”** for access level.
* Click **“Generate”**.
* Download the **AuthKey\_\<KeyID>.p8** file and store it securely.
* Note down the following:
  * **Key ID**: Available in the **“Keys”** section.
  * **Issuer ID**: Found at the top of the **“Keys”** page.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdvoajR4WewspVPog8qU8R5RrPtS7hm9dmh6RgHtp7z5gn266dohrb-HcEuu_vn563PaaW45D7nQ1FOw8YECkyxdCTip3DBIuwOu_F5MPMa4hMBWdEj8KswQw85piGQTNvBZS1Bwq7x6myTfjxNrSFWGnE?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

* Click on **“Shared Secret”** and note it down as well.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fxjq6il2khMzyWFD8fZuV%2FShareSecret1.jpg.png?alt=media&amp;token=04d338f0-f70d-4d80-a423-4effa5838786" alt=""><figcaption></figcaption></figure>

### **Step 3: Configure the Conscent Gateway**

#### **3.1 Access Conscent Gateway Configuration**

* Log in to your **Conscent** dashboard.
* Navigate to the **“Monetize”** section.
* Click on **“Payment Gateway”** and select **“In-App Purchase Apple”**.

#### **3.2 Input App and Key Details**

* Enter the **App Name** and **Bundle ID** obtained earlier.
* Upload the **AuthKey.p8** file.
* Enter the **Key ID, Shared Secret Key,** and **Issuer ID** in their respective fields.

#### **3.3 Save Configuration**

* Review all the entered information for accuracy.
* Click on **“Save Changes”** to finalize the gateway configuration.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcf3mot0l63cVjr53_fbvX_PIet987gdiMJ-8QTru7h-avbxABRlXMyJtmNPPFl4WowZKnMhTe7bc46S-xsgR_bjRX6Ch7nA3TDhyQGxoONVuBFh6-_DtR_e8_f92qppz_57Ha-wtVIlus6y9HuFT_Mhsxy?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

### **Step 4: Create In-App Purchase Products in App Store Connect**

#### **4.1 Create a Subscription Group**

* In App Store Connect, select your app from **“My Apps”**.
* In the sidebar under **“Monetization”**, click on **“Subscriptions”**.
* If **“Subscriptions”** is not visible, ensure all agreements in **“Agreements, Tax, and Banking”** are accepted.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcAFlCL3DyJo1yubMwdS_TpveYot3aJ5qeh1wp-6obDLzI9Go281ZuFx1SuLBl44gZ8PxQIIDBPPOgBzwfojxOrUcctL5Q1Ov7RfzqF7YrxIfd0_yxyg4_dT1Jwqsma9NSngnIbdIjZBqG1rcvO0jOpYN_-?key=812N5_E40exWAb14JOeSng" alt=""><figcaption></figcaption></figure>

* Click on **“Create”** to add a new Subscription Group.
* Enter a **Reference Name** for internal use (e.g., “Premium Access Subscriptions”).
* Click **“Create”**.

#### **4.2 Add a Subscription Product**

* Within the Subscription Group, click on **“Create”** to add a new subscription.
* Enter the following:
  * **Reference Name**: Internal name for the subscription (e.g., “Premium Annual Subscription”).
  * **Product ID**: A unique identifier (e.g., “com.yourapp.premium.annual”).
  * **Recommendation**: Use a consistent naming convention.
  * Click **“Create”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fi2lgNzbcJu6P29d2UtNa%2Fimage%20(11).png?alt=media&amp;token=220aa7bd-7e56-4b03-8501-15d383a2a579" alt=""><figcaption></figcaption></figure>

#### **4.3 Set Subscription Duration and Price**

* Under **“Subscription Duration”**, select the appropriate duration (e.g., “1 Year”).
* Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F8GsaNWAoZII36ZZ8vUTS%2Fimage%20(12).png?alt=media&amp;token=5794c00f-9712-4fe7-91ec-7b1a18d4282c" alt=""><figcaption></figcaption></figure>

* In the **“Subscription Prices”** section, click **“Add Subscription Price”**.
* Choose a price tier from the dropdown menu.
* Click **“Next”** and confirm the prices for all regions.
* Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fe2xBJwnQqsbwEt3ZpiKG%2Fimage%20(13).png?alt=media&amp;token=3210727c-536f-404c-a37c-2c7b7915ff73" alt=""><figcaption></figcaption></figure>

#### **4.4 Add Localization Information**

* In the **“App Store Information”** section, click on the **”+”** icon next to **“Localization”**.
* Select the desired language (e.g., “English (U.S.)”).
* Enter the following:
  * **Subscription Display Name**: Visible to users (e.g., “Premium Annual Access”).
  * **Description**: Detail what the subscription offers.
  * Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FPAX9uWhW0AfFP26E0ok0%2Fimage%20(14).png?alt=media&amp;token=f4efb12a-8295-4ec5-8ea1-5a79e6c6d4dc" alt=""><figcaption></figcaption></figure>

#### **4.5 Add Reviewer Information**

* In the **“Review Information”** section, upload a screenshot of your subscription purchase screen.
* **Note**: The screenshot must meet Apple’s requirements.
* Optionally, add **Review Notes** to provide additional information to the reviewer.
* Click **“Save”**.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FIsaBwznGofNhqxR7cjU4%2Fimage%20(16).png?alt=media&amp;token=8cd585ea-8ed3-45ae-b5d9-33dd5c72e17a" alt=""><figcaption></figcaption></figure>

### **Step 5: Configure Subscription Plans in Conscent Dashboard**

#### **5.1 Access Subscription Plans**

* In the Conscent Dashboard, navigate to the **“Subscriptions”** section.
* Click on **“Create Subscription Plan”**.

#### **5.2 Choose Subscription Type**

* Select **“In-App”** as the subscription type.
* Choose between **“Recurring Subscription”** or **“One-Time Subscription”** based on your product.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F3PPMejNfcRDdQAqb7kvH%2Fimage%20(18).png?alt=media&amp;token=7fc2f67a-b555-47d7-ab76-e5219bee0184" alt=""><figcaption></figcaption></figure>

#### **5.3 Configure Recurring Subscriptions**

* **Subscription Group Name**: Enter the name of the Subscription Group created in App Store Connect.
* **Apple Product ID**: Enter the **Product ID** of the subscription.
* **Duration**: Specify the subscription duration (e.g., “1 Year”).

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FkFhlXvnHfZtqOApFBGBy%2Fimage%20(20).png?alt=media&amp;token=579fea1e-03a5-43ba-a374-ca067b9a1ec8" alt=""><figcaption></figcaption></figure>

#### **5.4 Configure Non-Renewing Subscriptions**

* **Apple Product ID**: Enter the **Product ID** of the non-renewing subscription.
* **Duration**: Specify the access duration (e.g., “6 Months”).
* **Price**: Leave blank; pricing will be determined by the price tier set in App Store Connect.

#### **5.5 Save Subscription Plan**

* Provide the other parameters and review the entered details.
* Click **“Save”** to create the subscription plan.

### **Step 6: Provide Starting Price CSV to Conscent**

#### **6.1 Download Pricing CSV from App Store Connect**

* In App Store Connect, navigate to your subscription product.
* Under **“Subscription Prices”**, click on **“Download”**.
* A **.zip** file containing the **.csv** pricing information will be downloaded.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FE6aQeK8c5PKQ1SEt7SXV%2Fimage%20(21).png?alt=media&amp;token=d5586555-c6ac-4993-a023-e8674e1c156a" alt=""><figcaption></figcaption></figure>

#### **6.2 Provide Pricing CSV to Conscent**

* Extract the **.csv** file from the downloaded **.zip**.
* Upload the **.csv** file to the Conscent Dashboard or provide it to your Conscent representative.
* This allows Conscent to synchronize pricing across different regions.

<details>

<summary><mark style="color:orange;background-color:blue;"><strong>I</strong><strong>NFORMATION THAT NEED TO SHARED WITH CONSCENT</strong></mark></summary>

* App Name
* Bundle ID
* KeyId
* AuthKey.p8 file
* Issuer Id
* One-Time Subscription Plan- ProductId + Duration
* Renewal Subscription Plan - Group Name + productId + Duration&#x20;
* CSV file of both the plans(StartingPrice and CurrentPrice)

</details>

**Integrating App Store Server Notifications:**

We use App Store Server Notifications to track in-app purchase events in real time. By registering our web server’s HTTPS endpoint in App Store Connect, we receive direct notifications for subscription updates, renewals, and cancellations. Separate URLs are configured for production and sandbox environments, ensuring seamless testing and a reliable purchase experience.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FYWSoedCbsd3SJOZaZ0r2%2Fimage%20(3).png?alt=media&amp;token=9777bb4e-7d88-45c2-9941-1b941eb3a4ea" alt=""><figcaption></figcaption></figure>

### **Conclusion**

Your app is now ready to offer In-App Purchases to users, providing them with seamless access to your premium content. Should you require further assistance, please refer to Apple’s official documentation or contact Conscent team.

#### **Additional Resources**

* [Apple’s App Store Connect Help](https://help.apple.com/app-store-connect/)
* [In-App Purchase Programming Guide](https://developer.apple.com/in-app-purchase/)

**Note**: Always ensure compliance with Apple’s guidelines and review policies when setting up In-App Purchases to avoid any delays during the app review process.

Add the Conscent webhook URL to the Apple account.


# Facebook SSO Integration Guide

Welcome to the Facebook SSO Integration Guide. This document provides step-by-step instructions for integrating Facebook Login into your application, enabling users to authenticate with their Facebook credentials. This integration supports both web and mobile platforms (iOS and Android).

**Prerequisites:**

Before you begin, ensure you have the following:

* A registered Facebook Developer account.
* An app created in the Facebook Developer Console.
* Access to your application’s codebase (web or mobile).
* Your application’s redirect URLs (for web) or package names and key hashes (for mobile).

**Step 1: Create a Facebook App**

1. Log in to Facebook for Developers: Go to [developers.facebook.com](https://developers.facebook.com/) and log in with your Facebook account.
2. Create a New App:
   1. Click on **“My Apps”** in the top-right corner.
   2. Select **“Create App”**.
   3. Choose **“Consumer”** as the app type and click **“Next”**.
   4. Enter your **App Name** and **Contact Email**.
   5. Click **“Create App”** and complete any security checks.

**Step 2: Configure Your Facebook App**

1. **Obtain App ID and App Secret**
   1. In **“Settings” > “Basic”**, you will find your **App ID** and **App Secret**.
   2. **Important**: Keep your **App Secret** confidential.
2. **Whitelist Your SSO Domain**\
   \
   a. In your Facebook Developer Console, ensure your application’s domain is whitelisted:\
   \
   b. Go to “Settings” > “Basic”.\
   \
   c. Add your SSO domain(s) in the “App Domains” field.\
   \
   d. Ensure that your Bundle Identifier (iOS) and Package Name (Android) are correctly set for mobile apps.

**Step 3: Turn On Live Mode**

&#x20;    a. By default, If your app is in **Development Mode** and only accessible to admins, developers, and testers.

&#x20;    b. To make your app available to all Facebook users:

&#x20;    c. Go to the top bar of the dashboard.

&#x20;    d. Toggle the switch from **“In Development”** to **“Live”**.

**Note**: You may need to provide a privacy policy URL and adhere to Facebook’s platform policies.

**Conclusion**

By following this guide, you can integrate Facebook SSO into your application successfully. This will enhance user experience by providing a quick and secure login method.


# Landing Page API v 2.0

The landing page API enables clients to utilize their Subscription Landing Page and can be used to power subscription plans through Conscent.

> Create the subscription plans and landing pages on the Cosncent Dashboard before implementing the Landing Page API.

<mark style="color:green;">`GET{API_URL}`</mark><mark style="background-color:yellow;">/subscription/campaign?pathURL=Netflix\&clientId=5f92a62013332e0f667794dc</mark>

**PARAMS**

| Name     | Value                                                                                         |
| -------- | --------------------------------------------------------------------------------------------- |
| pathURL  | Same as the one present in Visualise ->  Subscriptions -> Landing Page -> CampaignURL         |
| clientId | [ClientId](https://sandbox-client.conscent.in/client/dashboard/Documentation) on th dashboard |

**Response**

{% tabs %}
{% tab title="200" %}

<pre class="language-json"><code class="lang-json"><strong>{
</strong>    "message": "Got landing page with the provided path",
    "isCampaignActive": true,
    "faviconUrl": "",
    "useClientFlow": false,
    "clientCampaignDetails": {
        "landingPage": {
            "customization": {
                "primaryColor": "#000000",
                "secondaryColor": "#d3ca6f",
                "buttonColor": "#000000",
                "buttonTextColor": "#f3fbf7",
                "priceTextColor": "#000000"
            },
            "title": "Test Subs123",
            "description": "Get access to world of quality content.",
            "headerRedirectUrl": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client-Story-Id-1",
            "desktopBannerUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Demo%20Client/banners/Demo%20Client%20-%20desktopBanner-f5a777.png",
            "mobileBannerUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Outlook/banners/Outlook%20-%20mobileBanner-4785ee.png",
            "brandLogoUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Demo%20Client/banners/Demo%20Client%20-%20brandLogo-d32f8b.png",
            "deletedAt": null,
            "_id": "6267f6b5a2d25f456bc69bc2",
            "clientId": "5f92a62013332e0f667794dc",
            "template": "t1",
            "createdAt": "2022-04-26T13:42:13.449Z",
            "updatedAt": "2023-12-01T12:13:02.429Z",
            "__v": 243
        },
        "subscriptions": [
            {
                "freeTrial": {
                    "enabled": false,
                    "duration": null
                },
                "benefits": "Benefit1,Benefit2,Benefit3", // Subscription benefits.
                "physical": false,
                "digital": true,
                "adFree": false,
                "migrated": false,
                "couponsEnabled": true,
                "adminCoupon": "",
                "usedCouponNumbers": [],
                "deletedAt": null,
                "_id": "61e93279bf6de47e4f6a676b",
                "recommended": false,
                "enabled": true,
                "clientId": "5f92a62013332e0f667794dc",
                "title": "Didi+Phy+Ad Free", // Title of the subscription
                "tiers": [
                    {
                        "priceOverrides": {
                            "country": []
                        },
                        "currency": "INR", // Currency of the user's country will be present here.
                        "basePrice": 0, // Base price which has been set in the client dashboard.
                        "offers": [
                            {
                                "_id": "617a703504ab353a12d84d2a",
                                "title": "IDFC Bank1",
                                "benefits": "This is the first benefit This is the first benefit This is the first benefit This is the first benefit This is the first benefit This is the first benefit ",
                                "iconUrl": "https://storage.googleapis.com/bkt-conscent-public-stage/Outlook/offers/617a703504ab353a12d84d2a-2f1c03.png"
                            }
                        ],
                        "_id": "61e93279bf6de47e4f6a676d",
                        "price": 6969, // Amount of the subscription
                        "duration": 12 // Duration in months
                    }
                ],
                "iconUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Outlook/subscriptions/61e93279bf6de47e4f6a676b-a6e1b9.png",
                "createdAt": "2022-01-20T09:59:22.673Z",
                "updatedAt": "2023-12-01T12:15:39.739Z",
                "__v": 22,
                "currencySymbol": "₹" // Currency symbol will change according to the currency.
            }
        ],
        "recommendedSub": ""
    },
    "clientId": "5f92a62013332e0f667794dc"
}
</code></pre>

{% endtab %}
{% endtabs %}


# AMP Integration

This code snippet is designed to work within an AMP HTML document. The code integrates various AMP-specific components and functionality, particularly focusing on content access and subscription management.

#### SANDBOX ENVIRONMENT: TESTING/STAGING ENVIRONMENT&#x20;

| API\_URL                                 | IFRAME\_URL                              |
| ---------------------------------------- | ---------------------------------------- |
| <https://sandbox-api.conscent.in/api/v2> | <https://v2-amp-sdk-sandbox.netlify.app> |

```javascript
<!DOCTYPE html>
<html amp lang="en">
  <head>
    <!-- If not Included -->
    <script
      async
      custom-element="amp-analytics"
      src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"
    ></script>

    <script id="amp-access" type="application/json">
      {
        "authorization": "{API_URL}/content/amp?rid=READER_ID&_=RANDOM&useRid=false&externalUserId={{userID}}&clientContentId=QUERY_PARAM(clientContentId)&clientId=QUERY_PARAM(clientId)&categories=QUERY_PARAM(categories)&tags=QUERY_PARAM(tags)&sections=QUERY_PARAM(sections)&authorName=QUERY_PARAM(authorName)&url=SOURCE_URL&title=QUERY_PARAM(title)",
        "pingback": "https://pub.com/amp-ping?rid=READER_ID&url=SOURCE_URL",
        "authorizationFallbackResponse": {
          "granted": true
        },
        "noPingback": true
      }
    </script>
  </head>

  <body>
  //added logout btn
     <div amp-access="logoutRedirectUrl" amp-access-hide>
          <div class="logout-container">
            <template amp-access-template type="amp-mustache">
              <button class="logout-button" id="logoutButtonConscent" on="tap:AMP.navigateTo(url='{{logoutRedirectUrl}}'),trackClick">Logout</button>
              </template>
          </div>
      </div>
      <div amp-access="NOT granted" amp-access-hide>
        <template amp-access-template type="amp-mustache">
          <amp-iframe
            id="conscentIframe"
            style="position: absolute; top: 0px; width: 100vw; height: 100vh"
            allowfullscreen
            width="100vh"
            height="50vh"
            src="{IFRAME_URL}/static/index.html?rid={{rid}}&clientId={{clientId}}&contentId={{contentId}}&journey={{journey}}&URL={{loginRedirectUrl}}&userId={{userId}}"
            layout="responsive"
            resizable
            id="myAmpIframe"
            sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"
          >
            <div
              style="
                position: absolute;
                top: 50%;
                left: 43%;
                display: flex;
                justify-content: center;
                align-items: center;
              "
              placeholder
            >
              <amp-img
                src="https://storage.googleapis.com/bkt-conscent-public-stage/808.gif"
                placeholder
                layout="fixed"
                width="140px"
                height="20px"
              ></amp-img>
            </div>
            <div overflow="">Read more!</div>
          </amp-iframe>
        </template>
      </div>

      <div amp-access="granted" amp-access-hide>
        <p>
          Early use Scientists are still debating when people started wearing
          clothes.
        </p>
        <template amp-access-template type="amp-mustache">
          <amp-iframe
            id="conscentIframe"
            style="position: absolute; top: 0px; width: 100vw; height: 100vh"
            allowfullscreen
            width="100vh"
            height="50vh"
             src="{IFRAME_URL}/static/index.html?rid={{rid}}&clientId={{clientId}}&contentId={{contentId}}&journey={{journey}}&URL={{loginRedirectUrl}}&userId={{userId}}"
            layout="responsive"
            resizable
            id="myAmpIframe"
            sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"
          >
            <div
              style="
                position: absolute;
                top: 50%;
                left: 43%;
                display: flex;
                justify-content: center;
                align-items: center;
              "
              placeholder
            >
              <amp-img
                src="https://storage.googleapis.com/bkt-conscent-public-stage/808.gif"
                placeholder
                layout="fixed"
                width="140px"
                height="20px"
              ></amp-img>
            </div>
            <div overflow="">Read more!</div>
          </amp-iframe>
        </template>
        <!-- Rest of the content here -->
        <div style="margin-top: 15px">
          <template amp-access-template type="amp-mustache">
            <div style="color: orange; font-size: 24px">
              -------Content Purchased------------
            </div>
            <p>Dynamic content: {{{cscContent}}}</p>
            Early use Scientists are still debating when people started wearing
            clothes. Estimates by various experts have ranged from 40,000 to 3
            million years ago. Some more recent studies involving the evolution
            of body lice have implied a more recent development with some
            indicating a development of around 170,000 years ago and others
            indicating as little as 40,000. No single estimate is widely
            accepted.
          </template>
        </div>
      </div>
  </body>
</html>
```


# Integrating APIs(v2)


# Purchase Details

This API gives the details of the subscription plans that the user has purcahsed.

## Get the details of previously purchased subscriptions.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/purchases/subscriptions`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name           | DataType      | Description                                                                                                 | Type     |
| -------------- | ------------- | ----------------------------------------------------------------------------------------------------------- | -------- |
| userId         | String        | user id of the user                                                                                         | Optional |
| from           | ISODateString | Start date-time for filtering purchases (ISO 8601 format)                                                   | Optional |
| to             | ISODateString | End date-time for filtering purchases (ISO 8601 format)                                                     | Optional |
| phoneNumber    | String        | phone number of the user                                                                                    | Optional |
| email          | String        | email of the user                                                                                           | Optional |
| status         | String        | <p>Subscription status filter (e.g. CHURNED, REVOKED, ACTIVE, INACTIVE, DELETED, REFUND\_INITIATED)<br></p> | Optional |
| updatedAtTo    | String        | Filter results for purchases updated before this date-time (ISO 8601 format)                                | Optional |
| updatedAtFrom  | String        | Filter results for purchases updated after this date-time (ISO 8601 format)                                 | Optional |
| pageNumber     | integer       | The page number for pagination                                                                              | Optional |
| pageSize       | integer       | The number of records per page for pagination                                                               | Optional |
| subscriptionID | String        | unique id of the subscription plan                                                                          | Optional |
| tierId         | String        | a unique identifier assigned to a plan based on duration                                                    | Optional |

**STATUS DEFINITION:**

**REVOKED:** The user's purchase access has been manually revoked, regardless of its validity.

**CHURNED:** The user's purchase renewal failed repeatedly and reached the retry limit.

**DELETED:** The user's purchase record has been permanently removed from the system.

**ACTIVE:** The user has a valid, active purchase granting access to services or features.

**INACTIVE:** The user had a purchase, but it has expired and is no longer valid.

**REFUND\_INITIATED:** A refund has been initiated for the user's purchase, pending processing.

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "purchases": [
        {
            "purchaseId": "6769b11d4440b23f3702cfdc",
            "userId": "6769a132112432faf3ddd8eb",
            "clientUserId": "facebook|186789117773895",
            "userEmail": "somi7@gmail.com",
            "userName": "Somi",
            "billingAddress": {
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "shippingAddress": {
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "userAddress": {
                "name": "",
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "clientReferenceId": null,
            "subscriptionId": "676902bhhc2a9c3ea8cc9535",
            "transactionId": "",
            "gatewayPaymentId": "",
            "status": "COMPLETE",
            "subscriptionName": "2024 Annual Print",
            "subscriptionRate": 0,
            "chargedAmount": 1,
            "chargedCurrency": "INR",
            "clientPrice": 1,
            "clientCurrency": "INR",
            "paymentSource": "",
            "paymentMethod": "",
            "taxInformation": [],
            "taxCountry": "IN",
            "subscriptionStatus": "ACTIVE",
            "daysSubscribed": 1064,
            "loginCountLast30Days": 0,
            "subscriptionType": "ONE_TIME",
            "subscriptionDetails": {
                "inrPrice": 23,
                "duration": 12,
                "originalSubscriptionPrice": 0,
                "durationType": "months"
            },
            "subcriptionTypeDetails": {
                "physical": false,
                "digital": true,
                "adFree": false,
                "epaper": false,
                "_id": "6769b11da67Jb23f3702cfde"
            },
            "revokedDate": null,
            "revokeStatus": false,
            "redeemedCouponCode": null,
            "renewedSubscriptionDetails": null,
            "manuallyRenewed": true,
            "renewSubscription": false,
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": null,
            "migrated": true,
            "clientId": "6734549778dfef5f987dfaf2",
            "clientContentId": null,
            "contentId": null,
            "buyingPrice": 23.128781252292132,
            "price": 23.128781252292132,
            "device": "desktop",
            "priceDetails": {
                "price": 1,
                "currency": "INR",
                "_id": "6769b56daca0b23f3702cfdd"
            },
            "expiryDate": "2025-03-19T00:00:00.000Z",
            "tierId": "676902bcec2a9c3ea8cc9544",
            "createdAt": "2022-04-20T00:00:00.000Z",
            "updatedAt": "2025-03-19T18:25:12.697Z",
            "partialAccess": false,
            "sectionsInclude": [],
            "authorsInclude": [],
            "sectionsExclude": [],
            "authorsExclude": [],
            "tagsInclude": [],
            "tagsExclude": []
        },
        {
            "purchaseId": "67dbc4d367bb918c385338f6",
            "userId": "6769a132112432faf3ddd8eb",
            "clientUserId": "facebook|1867891176583895",
            "userEmail": "somy@gmail.com",
            "userName": "Somi",
            "billingAddress": {
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "shippingAddress": {
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "userAddress": {
                "name": "",
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "clientReferenceId": null,
            "subscriptionId": "6769080754bad89ea134adaf",
            "transactionId": "",
            "gatewayPaymentId": "",
            "status": "COMPLETE",
            "subscriptionName": "2024 Annual",
            "subscriptionRate": 0,
            "chargedAmount": 99,
            "chargedCurrency": "INR",
            "clientPrice": 99,
            "clientCurrency": "INR",
            "paymentSource": "",
            "paymentMethod": "",
            "taxIncludedInPrice": true,
            "taxInformation": [
                {
                    "category": "DIGITAL",
                    "taxAmount": 4.714285714285714,
                    "taxBasePrice": 94.28571428571429,
                    "clientTaxAmount": 4.714285714285714,
                    "clientTaxBasePrice": 94.28571428571429,
                    "taxRate": 5,
                    "taxName": "VAT",
                    "_id": "67dbc4d367bb918c385338fa"
                },
                {
                    "category": "PHYSICAL",
                    "taxAmount": 0,
                    "taxBasePrice": 0,
                    "clientTaxAmount": 0,
                    "clientTaxBasePrice": 0,
                    "taxRate": 5,
                    "taxName": "VAT",
                    "_id": "67dbc4d367bb918c385338fb"
                }
            ],
            "taxCountry": "AE",
            "subscriptionStatus": "ACTIVE",
            "daysSubscribed": 36,
            "loginCountLast30Days": 0,
            "subscriptionType": "ONE_TIME",
            "subscriptionDetails": {
                "inrPrice": 2327.2765787573658,
                "duration": 12,
                "originalSubscriptionPrice": 0,
                "durationType": "months"
            },
            "subcriptionTypeDetails": {
                "physical": false,
                "digital": false,
                "adFree": false,
                "epaper": true,
                "_id": "67dbc4d367bb918c385338f8"
            },
            "revokedDate": null,
            "revokeStatus": false,
            "redeemedCouponCode": null,
            "renewedSubscriptionDetails": null,
            "manuallyRenewed": false,
            "renewSubscription": false,
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": null,
            "migrated": false,
            "clientId": "673454977d7bef5f987dfaf2",
            "clientContentId": null,
            "contentId": null,
            "buyingPrice": 2327.2765787573658,
            "price": 2327.2765787573658,
            "device": "desktop",
            "priceDetails": {
                "price": 99,
                "currency": "AED",
                "_id": "67dbc4d367bb918c385338f7"
            },
            "expiryDate": "2026-03-20T07:33:38.992Z",
            "tierId": "6769080754bad89ea134adb2",
            "createdAt": "2025-03-20T07:33:39.006Z",
            "updatedAt": "2025-03-20T07:33:39.006Z",
            "partialAccess": false,
            "sectionsInclude": [],
            "authorsInclude": [],
            "sectionsExclude": [],
            "authorsExclude": [],
            "tagsInclude": [],
            "tagsExclude": []
        },
        {
            "purchaseId": "67dbe416f8c9c703bd7d4226",
            "userId": "6769a132112432faf3ddd8eb",
            "clientUserId": "facebook|1867891176583895",
            "userEmail": "jojithomas57@gmail.com",
            "userName": "Joji Thomas",
            "billingAddress": {
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "shippingAddress": {
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "userAddress": {
                "name": "",
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "clientReferenceId": null,
            "subscriptionId": "6769030b54bad89ea13455ff",
            "transactionId": "",
            "gatewayPaymentId": "",
            "status": "COMPLETE",
            "subscriptionName": "2024 Annual offline",
            "subscriptionRate": 0,
            "chargedAmount": 30,
            "chargedCurrency": "AED",
            "clientPrice": 30,
            "clientCurrency": "AED",
            "paymentSource": "",
            "paymentMethod": "",
            "taxIncludedInPrice": true,
            "taxInformation": [
                {
                    "category": "DIGITAL",
                    "taxAmount": 1.4285714285714286,
                    "taxBasePrice": 28.571428571428573,
                    "clientTaxAmount": 1.4285714285714286,
                    "clientTaxBasePrice": 28.571428571428573,
                    "taxRate": 5,
                    "taxName": "VAT",
                    "_id": "67dbe416f8c9c703bd7d422a"
                },
                {
                    "category": "PHYSICAL",
                    "taxAmount": 0,
                    "taxBasePrice": 0,
                    "clientTaxAmount": 0,
                    "clientTaxBasePrice": 0,
                    "taxRate": 5,
                    "taxName": "VAT",
                    "_id": "67dbe416f8c9c703bd7d422b"
                }
            ],
            "taxCountry": "IN",
            "subscriptionStatus": "ACTIVE",
            "daysSubscribed": 36,
            "loginCountLast30Days": 0,
            "subscriptionType": "ONE_TIME",
            "subscriptionDetails": {
                "inrPrice": 705.2353268961715,
                "duration": 12,
                "originalSubscriptionPrice": 0,
                "durationType": "months"
            },
            "subcriptionTypeDetails": {
                "physical": false,
                "digital": true,
                "adFree": false,
                "epaper": false,
                "_id": "67dbe416f8c9c703bd7d4228"
            },
            "revokedDate": null,
            "revokeStatus": false,
            "redeemedCouponCode": null,
            "renewedSubscriptionDetails": null,
            "manuallyRenewed": false,
            "renewSubscription": false,
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": null,
            "migrated": false,
            "clientId": "673454977d7bef5f987dfaf2",
            "clientContentId": null,
            "contentId": null,
            "buyingPrice": 705.2353268961715,
            "price": 705.2353268961715,
            "device": "desktop",
            "priceDetails": {
                "price": 30,
                "currency": "INR",
                "_id": "67dbe416f8c9c703bd7d4227"
            },
            "expiryDate": "2026-03-20T09:47:02.083Z",
            "tierId": "6769030b54bad89ea1345602",
            "createdAt": "2025-03-20T09:47:02.099Z",
            "updatedAt": "2025-03-20T09:47:02.099Z",
            "partialAccess": false,
            "sectionsInclude": [],
            "authorsInclude": [],
            "sectionsExclude": [],
            "authorsExclude": [],
            "tagsInclude": [],
            "tagsExclude": []
        }
    ],
    "paginationInfo": {
        "pageNumber": 1,
        "pageSize": 100,
        "recordsReturned": 3,
        "totalCount": 3,
        "totalPages": 1
    }
}
```

{% endtab %}
{% endtabs %}


# User Registered Or Not

This API is used to identify if the user is registered or not.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/check-account-status-by-client`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name        | Type   | Description              |
| ----------- | ------ | ------------------------ |
| phone       | String | phone number of the user |
| countryCode | String | contryCode of phone No.  |
| email       | String | email of the user        |
| status      | CHURN  |                          |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which the user has registered.

```json
{
    "accountExists": false
}
```


# User Registrations

This API is used to identify if the user is registered or not.

<mark style="color:blue;">`POST`</mark> `{API_URL}/client/register-user`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name                | DataType | Description                                          | Type      |
| ------------------- | -------- | ---------------------------------------------------- | --------- |
| phone               | String   | phone number of the user                             | Optional  |
| countryCode         | String   | contryCode of phone No.                              | Optional  |
| email               | String   | email of the user                                    | Optional  |
| firstName           | string   | first name of the user                               | Mandatory |
| lastName            | string   | last name of the user                                | Optional  |
| dateOfBirth         | string   | dob of the user                                      | Optional  |
| gender              | string   | User's gender (Allowed values: MALE, FEMALE, OTHERS) | Optional  |
| enableOffers        | boolean  | Flag to enable promotional offers                    | Optional  |
| enableNotifications | boolean  | Flag to enable notifications                         | Optional  |

> You need to pass either below paarmeters of the user from which the user,

```json
{
    "firstName": "Shivam Dubey",
    "email": "shivamdubey+abcd@conscent.ai",
    "phone": "9807876896",
    "isEmailVerified": true,
    "isPhoneVerified": true,
    "countryCode": "+91",
    "gender": "MALE",
    "dateOfBirth": "2025-05-13T16:13:02.128Z",
    "shippingAddress": [
        {
            "apartment": "20/41 Rambagh",
            "city": "Agra",
            "state": "UP",
            "pincode": "282006",
            "country": "INDIA"
        },
        {
            "apartment": "20/41 Rambagh",
            "city": "Agra",
            "state": "UP",
            "pincode": "282007",
            "country": "INDIA"
        }
    ],
    "billingAddress": [
        {
            "apartment": "20/41 Rambagh",
            "city": "Agra",
            "state": "UP",
            "pincode": "8",
            "country": "INDIA"
        },
        {
            "apartment": "20/41 Rambagh",
            "city": "Agra",
            "state": "UP",
            "pincode": "282009",
            "country": "INDIA"
        }
    ]
}
```

{% tabs %}
{% tab title="201: Created " %}

```postman_json
{
    "message": "Account created successfully",
    "userId": "66ced0ebf72e8b7beddfe1e1"
}
```

{% endtab %}
{% endtabs %}


# Subscription Plans Details

This API retrieves the subscription plan details including subscription Id, Tier Id, price etc..

## Get the details of the subscription plans.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/subscription-plans`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name           | DataType | Description                                                                                                                                             | Type     |
| -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| from           | string   | Start date-time for filtering subscription plans (ISO 8601 format)                                                                                      | Optional |
| to             | string   | End date-time for filtering subscription plans (ISO 8601 format)                                                                                        | Optional |
| subscriptionId | string   | Subscription Id of the plan                                                                                                                             | Optional |
| pageNumber     | integer  | <p>It indicates the current page of results that the client is requesting from a larger dataset.<br><br>Default value is 10 Records in 1 pageNumber</p> | Optional |
| showRecords    | integer  | Total records that you want to show in a page no.                                                                                                       | Optional |

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "subscriptionPlans": [
        {
            "freeTrial": {
                "enabled": false,
                "duration": null
            },
            "_id": "66052fa93d9bc90560386b94",
            "benefits": "Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere,Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere,Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere, Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere,Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere,Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere, Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere,Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere,Digital Subscription Portable carry with you anytime anywhere , Locators- Id Portable carry with you anytime anywhere",
            "physical": true,
            "digital": true,
            "adFree": false,
            "couponsEnabled": true,
            "partialAccess": false,
            "sectionsInclude": [],
            "authorsInclude": [],
            "sectionsExclude": [],
            "authorsExclude": [],
            "tagsInclude": [],
            "tagsExclude": [],
            "title": "Pure Physcial",
            "tiers": [
                {
                    "priceOverrides": {
                        "country": []
                    },
                    "tierName": null,
                    "price": 500,
                    "currency": "INR",
                    "duration": 1,
                    "basePrice": 0,
                    "offers": [
                        "6618cc8791683113b883b45a",
                        "6618d6ab91683113b883b47b",
                        "6618da9a91683113b883b48f",
                        "6663078e93df6a052d62fdd1"
                    ],
                    "_id": "668665db404fa5123f1943cb"
                }
            ],
            "billingCycleType": "ONE_TIME",
            "iconUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/V2 Client 2/subscriptions/66052fa93d9bc90560386b94-b3ad67.png"
        }
    ],
    "pagination": {
        "totalRecords": 1,
        "pageNumber": 1,
        "pageSize": 50,
        "totalPages": 1
    }
}
```

{% endtab %}
{% endtabs %}


# Get User Details

This API retrieves user details for a specified time range. It supports filtering by userId, email, and signUpOriginUrl.

## Get the details of the user.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/userDetail`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name            | DataType | Description                                                                                                                                            | Type     |
| --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- |
| from            | string   | Start date-time for filtering users (ISO 8601 format)                                                                                                  | Optional |
| to              | string   | End date-time for filtering users (ISO 8601 format)                                                                                                    | Optional |
| email           | string   | emailId of the user                                                                                                                                    | Optional |
| signUpOriginUrl | string   | The URL from where the user has come.                                                                                                                  | Optional |
| userId          | string   |                                                                                                                                                        | Optional |
| gender          | string   | User's gender (Allowed values: MALE, FEMALE, OTHERS)                                                                                                   | Optional |
| dateOfBirth     | string   | dob of the user                                                                                                                                        | Optional |
| pageNumber      | integer  | <p>It indicates the current page of results that the client is requesting from a larger dataset.</p><p>Default value is 10 Records in 1 pageNumber</p> | Optional |
| pageSize        | integer  | Total records that you want to show in a page no.                                                                                                      | Optional |
| phone           | string   | phone no. of the user                                                                                                                                  | Optional |
| googleId        | string   |                                                                                                                                                        | Optional |
| appleId         | string   |                                                                                                                                                        | Optional |
| facebookId      | string   |                                                                                                                                                        | Optional |

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "data": [
        {
            "id": "67eca0ef9481efeabeb51368",
            "name": "Shivam Dubey",
            "email": "shivamdubey@conscent.ai",
            "shippingAddress": [],
            "billingAddress": [],
            "userAddress": {
                "name": "",
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "countryCode": "+91",
            "gender": "MALE",
            "dateOfBirth": "2025-04-01T00:00:00.000Z",
            "isPhoneVerified": false,
            "isEmailVerified": true,
            "hasPassword": false,
            "accessMethod": {
                "otp": false,
                "password": true
            },
            "createdAt": "2025-04-02T02:29:03.509Z",
            "updatedAt": "2025-04-29T15:28:22.514Z",
            "secondaryPhoneNumber": "9837394813",
            "googleId": "117611759572269030023",
            "appleId": "001350.26cfd198350448cb85e031480f577e67.0844",
            "signUpOriginUrl": "https://mock-client-demo-blog-v2-sandbox.netlify.app/politics"
        }
    ],
    "pageNumber": "1",
    "pageSize": "500",
    "countDocuments": 1
}
 
```

{% endtab %}
{% endtabs %}


# Add Subscription If User Registered

This API adds subscriptions to the Profile if the user is registerd.

## Add the subscriptions of the user.

<mark style="color:blue;">`POST`</mark> `{API_URL}/client/add-subscription`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name                  | Type          |
| --------------------- | ------------- |
| userId                | string        |
| purchaseId            | string        |
| subscriptionId        | string        |
| tierId                | string        |
| subscriptionStartDate | ISODateString |
| subscriptionEndDate   | ISODateString |

{% tabs %}
{% tab title="201: Created " %}

```json
{
    "userId": "66c71ff633fe796c9e382ad9",
    "purchaseId": "66ceba5a69b56840cd408da5",
    "subscriptionId": "6605323f3d9bc90560386b9f",
    "tierId": "6605323f3d9bc90560386ba1",
    "subscriptionStartDate": "2024-08-28T05:49:14.275Z",
    "subscriptionEndDate": "2024-09-22T04:30:00.000Z"
}
```

{% endtab %}
{% endtabs %}


# Update UserDetails

## Update details of the user

<mark style="color:blue;">`PATCH`</mark> `{API_URL}/client/update-user`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name   | Type           |
| ------ | -------------- |
| userId | Id of the user |

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fhgab2fTErWJf55H7FSi2%2FScreenshot%202025-02-17%20at%2011.32.05%20AM.png?alt=media&amp;token=91460842-f9ec-43e5-bbf0-50d1060e776c" alt=""><figcaption></figcaption></figure>

{% tabs %}
{% tab title="200: OK " %}

```
{
    "message": "User Details Updated Successfully.",
    "userData": {
        "status": "ACTIVE",
        "userId": "681c74b2333e169d16a7e58b",
        "name": "Shivam Dubey",
        "email": "shivamdubey+kljo@conscent.ai",
        "countryCode": "+91",
        "phone": "98679796896",
        "gender": "MALE",
        "dateOfBirth": "2025-05-13T16:13:02.128Z",
        "address": {
            "name": "",
            "apartment": "",
            "area": "",
            "pincode": "",
            "landmark": "",
            "city": "",
            "state": "",
            "country": ""
        },
        "usedCoupons": [],
        "clientSpecificIds": [],
        "migrated": false,
        "isPhoneVerified": true,
        "isEmailVerified": true,
        "shippingAddress": [
            {
                "name": "",
                "apartment": "20/41 Rambagh",
                "area": "",
                "pincode": "2820006",
                "landmark": "",
                "city": "Agra",
                "state": "UP",
                "country": "USA",
                "_id": "681c94453b8e51752d8b55d9"
            }
        ],
        "billingAddress": [
            {
                "name": "",
                "apartment": "20/41 Rambagh",
                "area": "",
                "pincode": "282008",
                "landmark": "",
                "city": "Agra",
                "state": "UP",
                "country": "USA",
                "_id": "681c94453b8e51752d8b55d8"
            },
            {
                "name": "",
                "apartment": "20/41 Rambagh",
                "area": "",
                "pincode": "282006",
                "landmark": "",
                "city": "Agra",
                "state": "UP",
                "country": "INDIA",
                "_id": "681c9aa0686c9aa662232d9a"
            }
        ],
        "createdAt": "2025-05-08T09:09:08.369Z",
        "updatedAt": "2025-05-08T11:50:56.442Z"
    }
}
```

{% endtab %}
{% endtabs %}

> You need to pass userIdof the user.


# Update SubscriptionDetails

## Update details of the user

<mark style="color:blue;">`PATCH`</mark> `{API_URL}/client/update-subscription/purchaseId:`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name                  | Type |
| --------------------- | ---- |
| subscriptionStartDate |      |
| subscriptionEndDate   |      |
| price                 |      |
| userCountry           |      |
| currency              |      |

> You need to pass purchaseId of  the user.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F5Ic1R0mWmVzwEQLQaxkq%2FScreenshot%202025-03-07%20at%204.57.20%20PM.png?alt=media&amp;token=914432c9-4363-4f49-99eb-327ec8ce77c5" alt=""><figcaption></figcaption></figure>


# Get All Transaction Details

## Get the details of transactions.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/get-all-transactions`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

<table><thead><tr><th width="165.96484375">Name</th><th>DataType</th><th>Description</th><th>Type</th></tr></thead><tbody><tr><td>from</td><td>ISODateString</td><td>Start date-time for filtering purchases (ISO 8601 format)</td><td>Optional</td></tr><tr><td>to</td><td>ISODateString</td><td>End date-time for filtering purchases (ISO 8601 format)</td><td>Optional</td></tr><tr><td>email</td><td>String</td><td>email of the user</td><td>Optional</td></tr><tr><td>userId</td><td>String</td><td></td><td>Optional</td></tr><tr><td>skip</td><td>integer</td><td></td><td>Optional</td></tr><tr><td>limit</td><td>integer</td><td></td><td>Optional</td></tr></tbody></table>

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "data": [
        {
            "_id": "68146e7e744b874f5775cfaa",
            "createdAt": "2025-05-02T07:04:30.071Z",
            "updatedAt": "2025-05-05T11:07:03.453Z",
            "userEmail": "cybercoupon@gmail.com",
            "userName": "AYUSH",
            "userAddress": {
                "name": "",
                "apartment": "",
                "area": "",
                "pincode": "",
                "landmark": "",
                "city": "",
                "state": "",
                "country": ""
            },
            "billingAddress": {
                "area": "",
                "pincode": "",
                "state": "",
                "country": "",
                "apartment": "",
                "landmark": "",
                "city": ""
            },
            "shippingAddress": {
                "area": "",
                "pincode": "",
                "state": "",
                "country": "",
                "apartment": "",
                "landmark": "",
                "city": ""
            },
            "userId": "6814639998f1ed0298475c6e",
            "clientReferenceId": "undefined",
            "transactionRefNumber": "7461694684236577604806",
            "orderId": "016153570198200",
            "contentId": null,
            "refundStatus": "INITIATED",
            "refundDetails": [
                {
                    "_id": "68189bd7ac8fc0629d1551b4",
                    "status": "PROCESSED",
                    "transactionId": "68146e7e744b874f5775cfaa",
                    "amount": 1.3,
                    "currency": "INR",
                    "purchaseType": "SUBSCRIPTION",
                    "user": "6814639998f1ed0298475c6e",
                    "clientId": "661907c2487ae1aba956dcc4",
                    "cancelAccess": true,
                    "rzpRefundId": "7464432229166504004806",
                    "refundObject": {
                        "refundResponse": {
                            "_links": {
                                "self": {
                                    "href": "/pts/v2/refunds/7464432229166504004806",
                                    "method": "GET"
                                },
                                "void": {
                                    "href": "/pts/v2/refunds/7464432229166504004806/voids",
                                    "method": "POST"
                                }
                            },
                            "id": "7464432229166504004806",
                            "submitTimeUtc": "2025-05-05T11:07:03Z",
                            "status": "PENDING",
                            "reconciliationId": "7461694684236577604806",
                            "clientReferenceInformation": {
                                "code": "6814639998f1ed0298475c6e"
                            },
                            "refundAmountDetails": {
                                "refundAmount": "0.06",
                                "currency": "AED"
                            }
                        }
                    },
                    "createdAt": "2025-05-05T11:07:03.375Z",
                    "updatedAt": "2025-05-05T11:07:03.375Z",
                    "__v": 0
                }
            ],
            "status": "COMPLETE",
            "subscriptionName": "kuchbhi rename ",
            "subscriptionId": "673c315bb2deb6e310fbd8f0",
            "tierId": "673c315bb2deb6e310fbd8f3",
            "purchaseId": "68146e7e744b874f5775cfad",
            "redeemedCouponCode": "KUCH20",
            "price": 2.305923441191124,
            "currency": "INR",
            "gateway": "CYBERSOURCE",
            "category": "SUBSCRIPTION",
            "paymentSource": "4242XXXXXXXX4242",
            "paymentSourceType": "CARD",
            "expiryDate": "2025-06-02T07:04:30.126Z",
            "taxBasePrice": 2.305923441191124,
            "taxInformation": [
                {
                    "category": "DIGITAL",
                    "taxAmount": 0.01,
                    "taxBasePrice": 0.1,
                    "clientTaxAmount": 0.01,
                    "clientTaxBasePrice": 0.1,
                    "taxRate": 10,
                    "taxName": "cgst",
                    "_id": "68146e7e744b874f5775cfc9"
                },
                {
                    "category": "PHYSICAL",
                    "taxAmount": 0,
                    "taxBasePrice": 0,
                    "clientTaxAmount": 0,
                    "clientTaxBasePrice": 0,
                    "taxRate": 20,
                    "taxName": "Sg",
                    "_id": "68146e7e744b874f5775cfca"
                }
            ],
            "taxCountry": "IN",
            "gstComponent": {
                "physical": 0,
                "digital": 0
            }
        }
    ],
    "count": [
        {
            "_id": "COMPLETE",
            "count": 1
        }
    ],
    "paginationInfo": {
        "pageNumber": 1,
        "pageSize": 100,
        "recordsReturned": 1,
        "totalCount": 1,
        "totalPages": 1
    }
}
```

{% endtab %}
{% endtabs %}

<pre class="language-json"><code class="lang-json"><strong>
</strong></code></pre>


# IAM System API Documentation

Overview:

The **IAM System API** allows you to manage client dashboard users, including creating, updating, and deleting users with specific permissions and roles. Authentication is done using Basic Auth with **`API_KEY`** and **`API_SECRET`.**

**Endpoints:**

### 1. Create Client Dashboard User

**Endpoint:**<mark style="color:green;">`POST`</mark> `{{BASE_URL}}v2/client/multi-user`

**Description:** Creates a new user with a specified email, password, role, and permissions.

All endpoints require Basic Authentication with the following headers:

**Headers**

<table><thead><tr><th width="305">Name</th><th>Value</th></tr></thead><tbody><tr><td>Content-Type</td><td><code>application/json</code></td></tr><tr><td>Authorization</td><td><code>Basic &#x3C;Base64Encoded(API_KEY:API_SECRET)></code></td></tr></tbody></table>

**Request Body**

```json
{
  "email": "user@example.com",
  "password": "Abc123",
  "permissions": {
    "ignite": true,
    "paywallBuilder": true,
    "popUpBuilder": true,
    "newsLetterBuilder": true,
    "meterBannerBuilder": true,
    "loginSetting": true,
    "manageSubscription": true,
    "audienceSegment": true,
    "journey": false,
    "payments": false,
    "taxation": true,
    "subscriptionPlan": true,
    "manualSubscriptions": true,
    "Checkout": true,
    "micropayments": true,
    "paymentGateway": true,
    "notifications": true,
    "billing": true,
    "documentation": true,
    "ga4": true,
    "export": true,
    "webhooks": true,
    "internalUser": true,
    "pdfManager": true
  },
  "role": "ADMIN"
}

```

**Response**

{% tabs %}
{% tab title="201" %}

```json
201 Created: User created successfully.
```

{% endtab %}
{% endtabs %}

## 2. Update Client Dashboard User Details

**Endpoint:**<mark style="color:green;">`PATCH`</mark> `{{BASE_URL}}v2/client/multi-user/{userId}`

**Description:** Updates an existing user's details, including email, password, role, and permissions.

All endpoints require Basic Authentication with the following headers:

**Headers**

<table><thead><tr><th width="261">Name</th><th>Value</th></tr></thead><tbody><tr><td>Content-Type</td><td><code>application/json</code></td></tr><tr><td>Authorization</td><td><code>Basic &#x3C;Base64Encoded(API_KEY:API_SECRET)></code></td></tr></tbody></table>

**Request Body:** Similar to Create User.

**Response**

{% tabs %}
{% tab title="200" %}

```json
 User updated successfully.
```

{% endtab %}
{% endtabs %}


# Version 1.0


# Getting Started

Welcome to <mark style="color:orange;">Conscent.ai.</mark>

Conscent.ai is the only platform that empowers your team with relevant insights and enables you to build and automate the entire user experience, from activation to retention. With everything under one hood, we have surfaced as the world's most comprehensive and complete technology stack that helps you activate, curate and retain more users, building better ads and subscription revenue.

This documentation covers all the steps for you to get set up with Conscent.ai - from registering your content, then integrating the paywall on your content pages, and targeting the right users based on the insights and as per your requirements after logging into your account via authorized credentials.


# On Board

* The first step is registering you with Conscent.ai. This process is done internally by our Onboarding & Integration Team. Your administrator will receive the login credentials (email & password) for the Dashboard on the registered email.&#x20;
* Initially, you must provide a default currency value for the 'price,' 'duration,' and optionally, geolocation overrides if you want geo-fenced pricing options. This process will ensure that all the premium content on your website/app is behind a paywall.
* By logging in to your Conscent.ai Dashboard and navigating to the[ Integrations Page](https://client.conscent.in/client/dashboard/Documentation) in the 'Documentation Tab,' you can view your active ClientId, API Key, and API Secret.

<details>

<summary>Login Links to Conscent.ai dashboard</summary>

#### Sandbox Link: <https://sandbox-admin.conscent.in/admin/dashboard>

#### Production Link: <https://admin.conscent.in/admin/dashboard>

</details>

{% hint style="info" %}
By logging in to your Conscent.ai Client Dashboard and navigating to the [Integrations Page](https://client.conscent.in/client/dashboard/Documentation) in the 'Documentation Tab', you can view your active ClientId, API Key, and API Secret.
{% endhint %}


# Using Conscent.ai

* To start creating content on Conscent.ai, you must follow the[ Authentication Guidelines](https://docs.conscent.ai/authentication). Conscent.ai will only allow authorized persons to create, view and edit content. The Client API Key and API Secret must be passed in Authorization Headers using Basic Authentication to use these APIs  (API Key as the username and API Secret as the password.

{% hint style="info" %}
Whenever you're utilizing the Web Integration Code or Calling any Conscent.ai APIs, you need to update the API\_URL and SDK\_URL variables based on your operating environment.
{% endhint %}

Conscent.ai provides two environments.&#x20;

#### SANDBOX ENVIRONMENT: TESTING/STAGING ENVIRONMENT (v1)

|                   SDK\_URL                   |                 API\_URL                 |
| :------------------------------------------: | :--------------------------------------: |
| <https://sandbox-sdk.conscent.in/csc-sdk.js> | <https://sandbox-api.conscent.in/api/v1> |

#### PRODUCTION ENVIRONMENT: PRODUCTION ENVIRONMENT

|               SDK\_URL               |                                     API\_URL                                     |
| :----------------------------------: | :------------------------------------------------------------------------------: |
| <https://sdk.conscent.in/csc-sdk.js> | [https://api.conscent.in/api/v1](#production-environment-production-environment) |


# Authentication

Conscent.ai uses API keys to allow access to the API to Create and Register any content with Conscent.ai. You can view your API Key and API Secret by logging in to your Conscent.ai Dashboard and navigating to the [Client Integrations Page](https://client.conscent.in/client/dashboard/Documentation).

{% hint style="info" %}
Please contact your administrator for the Login Credentials to access the Dashboard - provided on the official email address registered with Conscent.ai.
{% endhint %}

<details>

<summary>Conscent.ai expects the API Key and API Secret to be included as username and password, respectively, in BasicAuth Authorization in certain API requests (Ex. Create Content API utilized by the Client).</summary>

Attaching the snapshot below:

<img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FqGWaLxhWJHknUhL8ajFv%2FScreenshot%202023-05-31%20at%203.01.33%20PM.png?alt=media&amp;token=2999530a-3477-4b5d-9f71-3d6c3f6feb2e" alt="" data-size="original">

</details>

For passing the Authorization in this API in the [Registration](broken://pages/LUnDp9nvvmcXxk3VksCr) Section, you may create that key by using this command in the terminal:

```
echo -n "API KEY:API SECRET" | base64
```

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F4i2Eg2zfuGPjix6oeVnA%2FScreenshot%202023-06-04%20at%203.39.06%20PM.png?alt=media&amp;token=f93919a4-21b4-4364-a65e-0ce5d8b9d65a" alt=""><figcaption></figcaption></figure>


# Web SDK

Integrating Conscent.ai on your Website is a simple and direct process. You start by copying the code below within the script tags - and adding it to the header section of your Route Index file.

<details>

<summary><mark style="color:orange;">Including this code in the header section allows the Conscent.ai Script to be initialized.</mark></summary>

{% code title="ConsCent Paywall Initalization Script:" %}

```
<script>
  const clientId = '5f92a62013332e0f667794dc';
  (function (w, d, s, o, f, cid) {
    if (!w[o]) {
      w[o] = function () {
        w[o].q.push(arguments);
      };
      w[o].q = [];
    }
    (js = d.createElement(s)), (fjs = d.getElementsByTagName(s)[0]);
    js.id = o;
    js.src = f;
    js.async = 1;
    js.title = cid;
    fjs.parentNode.insertBefore(js, fjs);
  })(window, document, 'script', '_csc', {SDK_URL}, clientId);
</script>
```

{% endcode %}

</details>

{% hint style="info" %}
Ensure you replace the 'clientId' with your actual Client ID retrieved from the [Conscent.ai Dashboard](https://stage-client.tsbdev.co/client/dashboard/Documentation) and the {SDK\_URL} with the [SDK URL](broken://pages/EPJH1OVqWR9bKMAfBFta) of an environment you want to use.
{% endhint %}

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following function on all the content/article pages.

<details>

<summary><mark style="color:orange;">Initialization of the Paywall</mark></summary>

```javascript
const csc = window._csc;
csc('show');
csc('init', {
  debug: true, // can be set to false to remove sdk non-error log output
  contentId: contentId,
  subscriptionUrl: {clientSubscriptionUrl},
  signInUrl: {clientSignInUrl},
  clientId: clientId,
  title: contentTitle,
  categories: ["category1", "category2,"category3"],
  tags: ["free", "premium", "metered"],
  sections: ["section1", "section2","section3"],
  authorName: "name",
  publicationDate: ISOstring,
  successCallback: yourSuccessCallbackFunction,
  wrappingElementId: 'csc-paywall',
  fullScreenMode: 'false' // if set to true, the entire screen will be covered,
  onPGcrossClick:(data:any)=>{console.log(data)}
})
```

**Using Client Login System:**

```javascript
const csc = window._csc; csc('show');
csc('init', {
debug: true, // can be set to false to remove sdk non-error log output contentId: contentId,
subscriptionUrl: {clientSubscriptionUrl},
signInUrl: {clientSignInUrl},
clientId: clientId,
title: contentTitle,
categories: ["category1", "category2,"category3"],
tags: ["free", "premium", "metered"],
sections: ["section1", "section2","section3"],
authorName: "name",
successCallback: yourSuccessCallbackFunction,
wrappingElementId: 'csc-paywall',
fullScreenMode: 'false' // if set to true, the entire screen will be covered, 
cUID: 'clientUserId',
successCallbackForPaywallClick: yoursuccessCallbackForPaywallClick,
});
const yoursuccessCallbackForPaywallClick = (clickType: any) => { console.log(clickType);
},
```

</details>

We import the initialization script using the unique '\_csc' identifier and run the 'init' function by passing a number of parameters

<table><thead><tr><th width="225">Parameter</th><th width="319">Description</th><th>Default</th></tr></thead><tbody><tr><td><pre><code>contentId
</code></pre></td><td>The 'contentId' which should be identical to the Content Id by which the particular content is registered - in the Client CMS. This allows us to identify each piece of unique content for a client.</td><td>REQUIRED</td></tr><tr><td><pre><code>clientId
</code></pre></td><td>The 'clientId' is retrieved from the <a href="https://client.conscent.in/client/dashboard/Documentation">Client Integrations Page</a> of the ConsCent Client Dashboard.</td><td>REQUIRED</td></tr><tr><td><pre><code>title
</code></pre></td><td>The 'title' should be the Content Title by which the particular content is registered within the Client CMS.</td><td>REQUIRED</td></tr><tr><td><pre><code>wrappingElementId
</code></pre></td><td>'wrappingElementId' is the id of an element (e.g. a div with absolute positioning on your website) within which you want the paywall to be embedded. Your element should have a minimum width of 320 pixels and a minimum height of 550 pixels for the conscent.ai paywall to fit properly.</td><td>REQUIRED</td></tr><tr><td><pre><code>subscriptionUrl
</code></pre></td><td>The 'subscriptionUrl' is the link to the Subscription page of the client's website - in cases when a user would like to subscribe to the client's website for accessing the content offered.</td><td>OPTIONAL</td></tr><tr><td><pre><code>signInUrl
</code></pre></td><td>'signInUrl' is the link to the login page for already subscribed users on the client's platform - in cases when a user has already registered and paid for the client's subscription and would like to access content using their login credentials. Doing this will add a "Sign in here" text to be displayed below the "Subscribe" button.</td><td>OPTIONAL</td></tr><tr><td><pre><code>fullScreenMode
</code></pre></td><td>'fullScreenMode' can be set to 'true' or 'false' (strings) -- if true, the first screen of the paywall will cover the entire webpage. This is useful if you don't want the content page to be visible at all once the user proceeds with the payment.</td><td>REQUIRED</td></tr></tbody></table>

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FLJ9nF8iK5V8Gpy6ZADm3%2FScreenshot%202023-06-05%20at%2012.06.07%20AM.png?alt=media&amp;token=b741f192-e5a7-4475-9aa5-0341926d5fd6" alt="" width="563"><figcaption><p>Paywall</p></figcaption></figure>

<details>

<summary><mark style="color:orange;">SuccessCallback Function</mark></summary>

```
async function yourSuccessCallbackFunction(validationObject: any) {
  // Function to show the premium content to the User since they have paid for it via ConsCent
  // Here you should verify the  validationObject with our backend
  // And then you must provide access to the user for the complete content

  // example verification code:
  console.log('Initiating verification with conscent backend');
  const xhttp = new XMLHttpRequest(); // using vanilla javascript to make a post request
  const url = `${API_URL}/content/consumption/${validationObject.consumptionId}`;
  xhttp.open('POST', url, true);
  // e is the response event
  xhttp.onload = (e) => {
    const backendConfirmationData = JSON.parse(e.target.response);

    // verifying that the validation received matches the backend data
    if (
      validationObject.consumptionId === backendConfirmationData.consumptionId &&
      validationObject.payload.clientId === backendConfirmationData.payload.clientId &&
      validationObject.payload.contentId === backendConfirmationData.payload.contentId
    ) {
      // Validation successful
      console.log('successful validation');
      // accessContent would be your function that will do all the actions that need to be done to unlock the entire content
      accessContent(true);
    }
  };
  xhttp.send();
}
```

</details>

You need to implement a 'successCallback' function which will receive a response containing a validationObject shown below - indicating whether the user has purchased the content, or if the user has access to the content already since they have purchased it before, or whether the transaction has failed and the user has not purchased the content.

```
{ "message": "Content Purchased Successfully", 
"payload": { 
 "clientId": "5fbb40b07dd98b0e89d90a25",
 "contentId": "Client Content Id 5",
 "createdAt": "2020-12-29T05:51:31.116Z" 
 }, 
 "consumptionId": "a0c433af-a413-49e1-9f40-ce1fbd63f568",
 "signature": "74h9xm2479m7x792nxx247998975393x08y9hubrufyfy3348oqpqqpyg78fhfurifr3" 
 }
```

|     validationObject Field     |                                             Meaning                                            |
| :----------------------------: | :--------------------------------------------------------------------------------------------: |
| Content Purchased Successfully |                         The user has purchased content via Conscent.ai.                        |
|         accessTimeLeft         | The user has purchased the content previously and still has free access to consume the content |
|          consumptionId         |      To verify each unique transaction by a user on the client's content with Conscent.ai      |

*<mark style="color:orange;">Please ensure that you call this function on all your content pages so that we can track all the events and provide accurate analytics.</mark>*


# Login

This script can be called anywhere as you already have the SDK script in your header section.

<table><thead><tr><th>Parameters</th><th>Description</th></tr></thead><tbody><tr><td><pre><code>clientId
</code></pre></td><td><p></p><p>The 'clientId' is retrieved from the <a href="https://client.conscent.in/dashboard/integration">Client Integrations Page</a> of the ConsCent Client Dashboard.</p></td></tr><tr><td><pre><code>wrappingElementId
</code></pre></td><td>'wrappingElementId' is a mandatory string that is the id of an element (e.g. a div with absolute positioning on your website) within which you want the login popup to be embedded.</td></tr><tr><td></td><td></td></tr></tbody></table>

{% tabs %}
{% tab title="shell" %}

```sh
const csc = window._csc as any;
    csc('conscent-login', {
      debug: true,
      clientId: clientId,
      defaultEmail: defaultEmail || '',
      defaultName: defaultName || '',
      defaultPhone: defaultPhone || '',
      wrappingElementId: 'embed',
      successCallback: async (userDetailsObject: any) => {
        console.log('Success callback received from conscent login', userDetailsObject);
        setUserDetails(userDetailsObject);
        props.setShowLoginModal(false)
      },
      onCrossBtnClickSuccess: async () => {
        console.log('cross btn click successfully');
        props.setShowLoginModal(false)
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
```

{% endtab %}

{% tab title="javaScript" %}

```javascript
const csc = window._csc as any;
    csc('conscent-login', {
      debug: true,
      clientId: clientId,
      defaultEmail: defaultEmail || '',
      defaultName: defaultName || '',
      defaultPhone: defaultPhone || '',
      wrappingElementId: 'embed',
      successCallback: async (userDetailsObject: any) => {
        console.log('Success callback received from conscent login', userDetailsObject);
        setUserDetails(userDetailsObject);
        props.setShowLoginModal(false)
      },
      onCrossBtnClickSuccess: async () => {
        console.log('cross btn click successfully');
        props.setShowLoginModal(false)
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });

```

{% endtab %}

{% tab title="php" %}

```php
const csc = window._csc as any;
    csc('conscent-login', {
      debug: true,
      clientId: clientId,
      defaultEmail: defaultEmail || '',
      defaultName: defaultName || '',
      defaultPhone: defaultPhone || '',
      wrappingElementId: 'embed',
      successCallback: async (userDetailsObject: any) => {
        console.log('Success callback received from conscent login', userDetailsObject);
        setUserDetails(userDetailsObject);
        props.setShowLoginModal(false)
      },
      onCrossBtnClickSuccess: async () => {
        console.log('cross btn click successfully');
        props.setShowLoginModal(false)
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });

```

{% endtab %}
{% endtabs %}

After integrating the Login script, the Login popup appears on the screen which can be customizable for all the Clients.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FQFXbQDMz3K3iHFKJHirj%2FScreenshot%202023-06-02%20at%206.22.34%20PM.png?alt=media&amp;token=872423a9-50cb-4d2a-bba5-785e806b8e57" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F76hIkFNIOPztzT2LvTIr%2FScreenshot%202023-06-02%20at%206.23.11%20PM.png?alt=media&amp;token=c679c124-0124-4277-b9a5-666061045c73" alt="" width="372"><figcaption><p>Verify OTP Screen</p></figcaption></figure>


# Logout

Once the user logs in using the Login script, this logout script can then be called so that the user is logged out.

{% tabs %}
{% tab title="shell" %}

```sh
const callLogoutBtn = () => {
    const csc = window._csc as any;
    csc('logout', {
      debug: true,
      clientId: clientId,
      wrappingElementId: 'embed',
      logoutCallback: async () => {
        console.log('logout');
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
  };
```

{% endtab %}

{% tab title="javaScript" %}

```javascript
const callLogoutBtn = () => {
    const csc = window._csc as any;
    csc('logout', {
      debug: true,
      clientId: clientId,
      wrappingElementId: 'logout',
      logoutCallback: async () => {
        console.log('logout');
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
  };
```

{% endtab %}

{% tab title="php" %}

```php
const callLogoutBtn = () => {
    const csc = window._csc as any;
    csc('logout', {
      debug: true,
      clientId: clientId,
      wrappingElementId: 'logout',
      logoutCallback: async () => {
        console.log('logout');
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
  };
```

{% endtab %}
{% endtabs %}


# Amp Documentation

Accelerated Mobile Pages (AMP) is an open source project created to improve the performance of web pages for mobile devices.

**SANDBOX ENVIRONMENT: TESTING/STAGING ENVIRONMENT**

| AMP\_URL                          | API\_URL                          |
| --------------------------------- | --------------------------------- |
| <https://amp-sandbox.netlify.app> | <https://sandbox-api.conscent.in> |

{% hint style="info" %}
The URLs mentioned above need to be passed in the authorization API.&#x20;
{% endhint %}

A few points need to be noted:

> 1. If the content is opened and a meter banner is visible, the metering iframe gets initialized.
> 2. If the paywall needs to be shown, the paywall iframe gets initialized.
> 3. Otherwise, the content is opened through amp-access="granted".

<details>

<summary>Parameter Details</summary>

```
* denotes the mandatory parameters.
```

* clientContentId\*: A unique ID if each content
* clientId\*: ClientId present on the Conscent Dashboard.
* rid\*: Provided by the AMP ecosystem, this is a unique identifier of the Reader as seen by AMP. (<https://amp.dev/documentation/components/amp-access>)
* url\*: The source URL
* title\*: the title of the content.
* journey\*: {{journey}}   //This has to be passed as it is on the code//
* categories: category of the content
* tags: tag of the content
* sections: section of the content
* authorName: author of the content

</details>

```javascript
<!DOCTYPE html>
<html amp lang="en">
<head>
  <meta charset="utf-8" />
  <title>Hello, AMPs</title>
  <link rel="canonical" href="https://amp.dev/documentation/guides-and-tutorials/start/create/basic_markup/" />
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1" />
  <style amp-boilerplate>
    body {
      -webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      -moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      -ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      animation: -amp-start 8s steps(1, end) 0s 1 normal both;
    }

    @-webkit-keyframes -amp-start {
      from {
        visibility: hidden;
      }

      to {
        visibility: visible;
      }
    }

    @-moz-keyframes -amp-start {
      from {
        visibility: hidden;
      }

      to {
        visibility: visible;
      }
    }

    @-ms-keyframes -amp-start {
      from {
        visibility: hidden;
      }

      to {
        visibility: visible;
      }
    }

    @-o-keyframes -amp-start {
      from {
        visibility: hidden;
      }

      to {
        visibility: visible;
      }
    }

    @keyframes -amp-start {
      from {
        visibility: hidden;
      }

      to {
        visibility: visible;
      }
    }
  </style>
  <noscript>
    <style amp-boilerplate>
      body {
        -webkit-animation: none;
        -moz-animation: none;
        -ms-animation: none;
        animation: none;
      }
    </style>
  </noscript>
  <style amp-custom>
    h1 {
      margin: 0px;
    }

    .iframe-container-inarticle {
      width: 550px;
      max-width: 100vw;
      height: 520px;
      position: absolute;
      top: 200px;
      text-align: left;
    }
  </style>
  <script async src="https://cdn.ampproject.org/v0.js"></script>
  <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
  <script async custom-element="amp-access" src="https://cdn.ampproject.org/v0/amp-access-0.1.js"></script>
  <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
  <script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
  <script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
  <script id="amp-access" type="application/json">
    {
      "authorization": "https://api.conscent.art/api/v1/content/amp?rid=READER_ID&_=RANDOM&clientContentId=QUERY_PARAM(clientContentId)&clientId=QUERY_PARAM(clientId)&categories=QUERY_PARAM(categories)&tags=QUERY_PARAM(tags)&sections=QUERY_PARAM(sections)&authorName=QUERY_PARAM(authorName)&url=SOURCE_URL",
      "pingback": "https://pub.com/amp-ping?rid=READER_ID&url=SOURCE_URL",
      "authorizationFallbackResponse": {
        "granted": true
      },
      "noPingback": true
    }
  </script>
</head>
<body>
  <div>
    <h1 id="hello">Hello AMP page!</h1>
    <p>Early use Scientists are still debating when people started wearing clothes. Estimates by various experts have
      ranged from 40,000 to 3 million years ago. Some more recent studies involving the evolution of body lice have
      implied a more recent development with some indicating a development of around 170,000 years ago and others
      indicating as little as 40,000. No single estimate is widely accepted.</p>
    <!-- if inarticle then wrap inside this <div class="iframe-container-inarticle"></div> -->
    <div amp-access="(NOT granted OR meteringActionId) AND isInArticle" amp-access-hide class="inarticle-style">
      <template amp-access-template type="amp-mustache">
        <amp-iframe id="conscentIframe" style="position: absolute;top: 0px;width: 100vw;height: 100vh;" allowfullscreen
          width="100vh" height="50vh"
          src="http://localhost:3008/index.html?rid={{rid}}&clientId={{clientId}}&contentId={{contentId}}&journey={{journey}}&URL={{url}}"
          layout="responsive" resizable id="myAmpIframe"
          sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation">
          <div style="position: absolute;top: 50%;left: 43%;display: flex;justify-content: center;align-items: center;"
            placeholder>
            <amp-img src="https://storage.googleapis.com/bkt-conscent-public-stage/808.gif" placeholder layout="fixed"
              width="140px" height="20px"></amp-img>
          </div>
          <div overflow="">Read more!</div>
        </amp-iframe>
      </template>
    </div>
    <div amp-access="(NOT granted OR meteringActionId) AND (NOT isInArticle)" amp-access-hide
      style="position: fixed; top: 0px">
      <template amp-access-template type="amp-mustache">
        <amp-iframe id="conscentIframe" style="position: absolute;top: 0px;width: 100vw;height: 100vh;" allowfullscreen
          width="100vh" height="50vh"
          src="http://localhost:3008/index.html?rid={{rid}}&clientId={{clientId}}&contentId={{contentId}}&journey={{journey}}&URL={{url}}"
          layout="responsive" resizable id="myAmpIframe"
          sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation">
          <div style="position: absolute;top: 50%;left: 43%;display: flex;justify-content: center;align-items: center;"
            placeholder>
            <amp-img src="https://storage.googleapis.com/bkt-conscent-public-stage/808.gif" placeholder layout="fixed"
              width="140px" height="20px"></amp-img>
          </div>
          <div overflow="">Read more!</div>
        </amp-iframe>
      </template>
    </div>
    <div amp-access="granted" amp-access-hide>
      <p>Early use Scientists are still debating when people started wearing clothes. </p>
      <!-- Rest of the content here -->
      <div style="margin-top: 15px">
        <template amp-access-template type="amp-mustache">
          <p>Dynamic content: {{{cscContent}}}</p>
          Early use Scientists are still debating when people started wearing clothes. Estimates by various experts have
          ranged from 40,000 to 3 million years ago. Some more recent studies involving the evolution of body lice have
          implied a more recent development with some indicating a development of around 170,000 years ago and others
          indicating as little as 40,000. No single estimate is widely accepted.Early use Scientists are still debating
          when people started wearing clothes.No single estimate is widely accepted.Early use Scientists are still debating
          when people started wearing clothes. Estimates by various experts have
          ranged from 40,000 to 3 million years ago.
        </template>
      </div>
    </div>
  </div>
</body>
</html>
```

<details>

<summary><strong>Configuration on dashboard</strong></summary>

1. Enter the Standard Pages homepage URL in the Login Settings under the Visualise Section on the [Conscent Dashboard.](https://client.conscent.in/client/dashboard/login-setting)

<img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fi378qaA8QvQF53hOHSQL%2FScreenshot%202024-04-15%20at%2011.13.34%20AM.png?alt=media&amp;token=6f06b09a-1c08-48a4-81d6-36750412e9b2" alt="" data-size="original">

2. After entering the URL, call the Auto-Login Code on the same website/page.

[Note: ](https://client.conscent.in/client/dashboard/login-setting)Attaching the link to navigate to the script - <https://docs.conscent.ai/auto-login>

</details>


# Mobile SDK

A Mobile SDK is a software package that contains a set of tools that can help to build platform-specific mobile applications and implement new features in existing mobile apps.


# Android

This is a step by step guide to include Conscent.ai Plugin in your app. This plugin is developed in Kotlin and supports both Java and Kotlin languages.

#### Pre-Requisites

Conscent.ai Android SDK supports **API 21 (Android 5.0)** and above. Please ensure the minSdkVersion is in the app's **build.gradle** file reflects the same.

{% hint style="info" %}
&#x20;*In case of an error for Kotlin not enabled - Enable Kotlin for Project.*

*In case of an error in Manifest merging - Merge Manifest as per Android Studio support or include the below line inside your application tag in the Android Manifest file.*

<pre class="language-xml" data-full-width="false"><code class="lang-xml"><strong>tools:replace="android:icon,android:roundIcon" 
</strong></code></pre>

{% endhint %}

#### Permissions

Add the following permissions to the `AndroidManifest.xml` file.

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

<details>

<summary>Installation</summary>

You can download and add AAR File from [here](https://github.com/tsbmediaventure/ConsCent-docs/tree/master/docs/plugins/android), which needs to be included in your **Module libs directory,** and tell gradle to install it like this:

```
Both files are required to be added.
```

```gradle
dependencies {
    implementation fileTree(include: [ '*.aar'], dir: 'libs')
}
```

</details>

<details>

<summary>Dependencies</summary>

In root level (project level) build.gradle, add classpath, and maven:

```gradle
dependencies {
    classpath 'com.google.gms:google-services:[latest-version]'
    // Add the Crashlytics Gradle plugin
    classpath 'com.google.firebase:firebase-crashlytics-gradle:[latest-version]'
}
```

In your application build.gradle file, include dependency as below with the latest versions:

```kotlin
dependencies{
// Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.9'
// Coroutines    
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
// Browser   
     implementation 'androidx.browser:browser:1.5.0'
     implementation 'com.google.android.gms:play-services-base:[latest-version]'
     implementation (platform("com.google.firebase:firebase-bom:[latest-version]"))
     implementation ("com.google.firebase:firebase-analytics-ktx")
     implementation ("com.google.firebase:firebase-crashlytics-ktx")
     implementation 'com.squareup.picasso:picasso:[latest-version]'
     implementation "androidx.swiperefreshlayout:swiperefreshlayout:[latest-version]"
}
```

</details>

<details>

<summary>Initialize SDK</summary>

In your application or root activity class's method onCreate, pass these fields to be used in your app.

* applicationContext - Pass your application context.
* yourClientId - Pass your clientId received from Conscent.ai.
* yourAccentColor - Pass your accentColor for the app.
* Mode - configuration testing of different environments available. &#x20;
* APP\_MODE - used for checking the debug and production environment of the app.  &#x20;

```kotlin
Api Mode can be set as :
    ConscentConfiguration.MODE.SANDBOX
    ConscentConfiguration.MODE.PRODUCTION
```

&#x20;                                               &#x20;

```kotlin
APP_MODE can be set as : 
    ConsCentConfiguration.APP_MODE.DEBUG 
    ConsCentConfiguration.APP_MODE.PROD
```

*If APP\_MODE is DEBUG, all errors will be shown as Toast messages and Logs.*&#x20;

*If APP\_MODE is PROD, only logs will be available for critical errors like Network unavailability, wrong client\_id, and wrong content\_id.*

</details>

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
class TestingApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        ConscentWrapper.configure(
            application = this,
            clientId = "5f92a62013332e0f667794dc",
            colorAccent = Color.parseColor("#000000"),
            appMode = ConscentConfiguration.APP_MODE.DEBUG,
            apiMode = ConscentConfiguration.MODE.SANDBOX,
        )
    }
}

```

{% hint style="info" %}
Pass the client ID received from Conscent.ai dashboard
{% endhint %}
{% endtab %}

{% tab title="Java" %}

```java
public class TestingApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        ConscentWrapper.Companion.configure(
                this,
                "5f92a62013332e0f667794dc",
                Color.parseColor("#000000"),
                ConscentConfiguration.APP_MODE.DEBUG,
                ConscentConfiguration.MODE.SANDBOX
        );
        
    }
}
```

{% hint style="info" %}
Pass the client Id received from Conscent.ai dashboard
{% endhint %}
{% endtab %}
{% endtabs %}

**Initialize the paywall**

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following method on all the content/article pages.

To have more control over the content flow, create an instance of the Conscent class inside your activity onCreate method for each unique contentId(recommended).

Use the below-described method:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
val instance = ConscentWrapper.getConscentInstance(
            callingActivity = yourCallingActivity,
            parentView = yourParentView,
            containerView = yourContainerView,
            popUpContainer = yourPopUpContainerView,
            onConscentListener = onConscentListener,
            contentId = contentId,
            title = contentTitle,
            categories= arrayListOf("categorie1","categorie2","categorie3"),
            sections = arrayListOf("section","section1","section3"),
            tags = arrayListOf("premium"),
            url = ContentUrl,
            authorName = authorName,
        )
//To display the registration paywall 
  RegistrationPaywall.initRegistrationPaywall()
 //To display the paywall       
RegularPaywall.initRegularPaywall()
//To display the metered banner
MeterBanner.initMeterBanner()
```

{% endtab %}

{% tab title="Java" %}

```java
Conscent instance = ConscentWrapper.Companion.getConscentInstance(
        yourCallingActivity,
        yourParentView,
        yourContainerView,
        yourPopUpContainerView,
        contentId,
        contentTitle,
        onConscentListener,
        Arrays.asList("categorie1", "categorie2", "categorie3"),
        Arrays.asList("section1", "sectio2", "section3"),
        Arrays.asList("premium"),
        contentUrl,
        authorName
);
 //To display the registration wall 
RegistrationPaywall.initRegistrationPaywall()
 //To display the paywall       
RegularPaywall.initRegularPaywall()
//To display the metered banner
MeterBanner.initMeterBanner()
```

{% endtab %}
{% endtabs %}

> #### Note: Include the AAR files of respective paywalls and banners before calling above functions.

#### To set the scroll depth on the content page:

```kotlin
instance.scrollDepth = scrollY
```

Call the below sample method on override **onActivityResult** in Activity Class.

```kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        Log.i(TAG, "RedirectionHandler.onActivityResult: ")
        if (resultCode == RESULT_OK) {
            if (data?.getStringExtra("TYPE") == "PLANS") {
                instance.checkSubscriptions(
                    TestingPreferences.getContentTitle(),
                    TestingPreferences.getSubscriptionUrl(),
                )
            } else
                instance.handledIntent()
        }
    }
```

In case of Fragment, call the below method inside onDestoyView()-

```
instance.onDestroy()
```

<table><thead><tr><th width="294.5">Parameters</th><th>Description</th></tr></thead><tbody><tr><td>yourCallingActivity(Activity)</td><td>This is your activity content which is calling the methods and where callback will be received.</td></tr><tr><td>yourParentView(ConstraintLayout)</td><td>This will be the parent of your layout. Please keep ConstraintLayout as your root view in your activity xml file. Pass the reference of your root view in checkContent function.  </td></tr><tr><td>yourContainerView(FrameLayout)</td><td><p>This will be a FrameLayout where the payment page will be inflated. Create a frameLayout in your XML and pass it here as a reference.</p><p>For eg:</p><pre class="language-xml"><code class="lang-xml">&#x3C;FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</code></pre></td></tr><tr><td>contentId (String)</td><td>This will be your article or content id for which detail needs to be checked.</td></tr><tr><td>yourContentTitle (<code>String</code> - Optional)</td><td>Title of the content for display purposes.</td></tr><tr><td>yourSubsUrl (<code>String</code> - Optional)</td><td>Url is to be used when subscribe button is clicked.</td></tr><tr><td>canSubscribe (<code>Boolean</code> - Optional)</td><td>Pass this as "true" to show subscribe layout else as "false".</td></tr><tr><td>showClose (<code>Boolean</code> - Optional)</td><td>Pass this as "true" to show the close button on the paywall/subscriptions, the default value is <code>"false"</code></td></tr><tr><td>OnConscentListener</td><td>You can pass a listener which will get called after success or failure in processing. If you pass a listener, after successful processing, the success reference will be called and for a failed event, the failure event will be called</td></tr></tbody></table>

You can implement OnConscentListener in your activity and then pass it as a reference.

| Methods                | Description                                                                                                                                                                                                                                                        |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| onSuccess              | This is the success callback that will get called for every successful processing. You can pass your method as a reference or a lambda expression which will get called in case of success.                                                                        |
| onError (optional)     | You can pass it as null. This is the failure callback which will get called for every failed processing. You can pass your method as a reference or a lambda expression and it'll get called for failed cases. You can implement your code in it for failed cases. |
| onSubscribe (optional) | If you want to inflate subscribe layout, pass a subscribe function which will be called when subscribe button will be clicked inside the payment flow. Passing null will not inflate subscribe layout.                                                             |
| onBuyPass (optional)   | It will be called when the buy-pass button will be clicked inside the payment flow.                                                                                                                                                                                |
| onSignIn               | This is the callback function that will be called when a user clicks on signIn button in the payment flow. This will be only visible if subscribe layout has been inflated.                                                                                        |
| onAdFree               | This is the callback function which will be called when a user clicks on adfree subscription.                                                                                                                                                                      |
| eventParams            | This callback function will be called when a user clicks on the Google login. This will send params paywallId,contentId, paywallType, clientId, and anonId.                                                                                                        |
| onShowPaywall          | This callback function will be called when a paywall is visible on the screen. This will send params - eventLocation, eventType, paywallDisplayType, paywallType.                                                                                                  |
| onGoogleLoginClick     | This will be used to trigger your Google sign. This callback function will be called when a user clicks on the Google login.                                                                                                                                       |
| onCustomLinkSlot       | This will be triggered when the Link Slot To on the Conscent Dashboard is linked to Custom URL                                                                                                                                                                     |

#### To check if an article/content is free/paid or payment needs to be done, in your class, use as below sample: Parameters detail can be checked below for more information.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
instance.checkContentAccess(
        yourContentTitle,
        yourSubsUrl,
        canSubscribe,
        showClose
    )
```

{% endtab %}

{% tab title="Java" %}

```java
instance.checkContentAccess(
        yourContentTitle,
        yourSubsUrl,
        canSubscribe,
        showClose
    );
```

{% endtab %}
{% endtabs %}

> Call <mark style="color:orange;">**checkContentAccess**</mark> method on override <mark style="color:orange;">**onNewIntent**</mark> method in Activity Class.

**Call the below function and pass the userId, after the user has logged in:**

```kotlin
PluginPreferences.setClientUserId("Your_User_Id")
```

#### To use only the Subscription Landing Page, call the below method:

> Create a singleton instance as done during initialization of the paywall.

```kotlin
instance.onSoftSubscribeClick(<subsUrl>)
```

<details>

<summary>Login Functionality</summary>

Call this method to invoke our Login System

```kotlin
ConscentWrapper.INSTANCE?.onlyLoginFlow(yourCallingActivity)
```

</details>

#### Logout the User:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
ConscentWrapper.INSTANCE?.logoutUser()
```

{% endtab %}

{% tab title="Java" %}

```java
ConscentWrapper.Companion.INSTANCE?.logoutUser();
```

{% endtab %}
{% endtabs %}

**Demo App:** [**Link**](https://github.com/RoshanSharma8245/Demo-Blog)


# Flutter

This is a step-by-step guide to including Conscent.ai Plugin in your app. This plugin is developed in Flutter and supports both Android and IOS Devices.

<mark style="color:orange;">**Installation**</mark>

#### Use [this](https://pub.dev/packages/flutter_conscent_plugin/install) package as a library

Depend on it

Run this command with Flutter:

```bash
flutter pub add flutter_conscent_plugin
```

This will add a line like this to your package's pubspec.yaml (and run an implicit `flutter pub get`):

```yaml
dependencies:
  flutter_conscent_plugin: ^0.4.2
```

Alternatively, your editor might support `flutter pub get`. Check the docs for your editor to learn more.

#### Import it

Now in your Dart code, you can use:

```dart
import 'package:flutter_conscent_plugin/flutter_conscent_plugin.dart';
```

<details>

<summary><mark style="color:orange;">Initialize SDK</mark></summary>

In your application pass these fields in your app.

* client\_id - Pass your clientId received from Conscent.ai.
* ENVIRONMENTMODE -  configuration testing of different environments available.&#x20;

```dart
ENVIRONMENTMODE can be set as :
    ENVIRONMENTMODE.SANDBOX 
    ENVIRONMENTMODE.PRODUCTION
```

The below code can be used as a sample:

```dart
ConscentInitializer("your_client_id", ENVIRONMENTMODE.SANDBOX);
```

</details>

<mark style="color:orange;">**Initialize Paywall**</mark>

1. Pass client content id in **setContentId(clientContentId)** Method:

Attaching the code below for the refernce:

```dart
ConscentInitializer.setContentId('your_content_id');
```

2. Check content access and show the paywall:

```dart
bool showContent = false;

 FutureBuilder<bool>(
  future: ConscentMethods().getContentAccess(),
  builder: (context, snapshot){
  
  if (snapshot.hasData) {
       var responseData = snapshot.data;
         if (responseData != null) {
           showContent = responseData;
         }
       
       return Center(
                  child: Stack(
                    children: <Widget>[
                      SingleChildScrollView(
                        controller: scrollController,
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.height,
                          padding: const EdgeInsets.all(20.0),
                          alignment: Alignment.topCenter,
                          child: YourContentPage(),
                        ),
                      ),
                      if (!showContent)
                        Container(
                            width: MediaQuery.of(context).size.width,
                            height: MediaQuery.of(context).size.height,
                            alignment: Alignment.bottomCenter,
                            child: Paywall((response) {
                              if (responseData != null) {
                                  showContent = responseData;
                              }
                              setState(() {});
                            })),
                    ],
                  ),
                );
               
  }else if (snapshot.hasError) {
    return ShowYourErrorPage();
  }
 },
), 
```

> *<mark style="color:orange;">These methods need to be called on the Content Page.</mark>*

<mark style="color:orange;">**Handling Events**</mark>

1. **Scroll Listener Event**

```dart
scrollController.addListener(() {
      onScollDepth = max(scrollController.offset, onScollDepth);
      height = scrollController.position.maxScrollExtent;

      ConscentMethods().setScollDepthHeight(onScollDepth, height);

      ConscentMethods().onTouchListener();
    });
```

2. **Exit from the Content page**

```dart
@override
void dispose() {
  super.dispose();
  ConscentMethods().pageExitEvent();
}
```

#### The below method is called to Logout from Conscent.ai

```dart
ConscentMethods().userLogOut()
```


# iOS(Swift)

This guide provides step-by-step instructions on how to include the Conscent.ai Plugin in your iOS app. The Conscent.ai Plugin is developed in swift Language.

**Pre-requisites**

&#x20;Conscent.ai iOS SDK supports **iOS 13.0** and above.

<details>

<summary>Installation Steps</summary>

You can download the CCPlugin.xcframework File from [here](https://github.com/tsbmediaventure/ConsCent-docs/tree/master/docs/mobile/IOS%20V1%20SDK) and add it to your project.

Make sure you change the embed mode for CCPlugin.xcframework to "**Embed & Sign**".

</details>

<details>

<summary>Initialize the SDK</summary>

1. Import the CCPlugin framework into your ViewController class.

```swift
import CCPlugin
```

2. In your ViewController class, configure the plugin by providing the client ID and the desired environment mode.

```swift
CCPlugin.shared.configure(mode: .sandbox, clientID: "your-client-id")
```

* yourClientId - Pass your clientId received from Conscent.ai.
* Mode - configuration testing of different environments available.&#x20;

<pre class="language-swift"><code class="lang-swift"><strong>Api Mode can be set as :
</strong>   Mode.sandbox
   Mode.production
</code></pre>

3. You need to set the scrollDepth for the paywall by accessing the scrollDepth property of the CCPlugin.shared instance and modifying its value.

```swift
// Retrieve and set the scroll depth
let screenHeight = scrollView.bounds.height
let scrollDepth: Int = Int(scrollView.contentOffset.y)
CCplugin.shared.scrollDepth = scrollDepth
```

4. You have to confirm UIScrollViewDelegate and you need to set scrollDepth and scrollDepthPercentage.

```swift
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let scrollDepth: Int = Int(scrollView.contentOffset.y)
    CCplugin.shared.scrollDepth = scrollDepth
    let contentHeight = scrollView.contentSize.height
    let scrollViewHeight = scrollView.bounds.height
    let scrollOffset = scrollView.contentOffset.y
    // Calculate the scroll percentage
    let scrollDepthPercentage = (scrollOffset / (contentHeight - scrollViewHeight)) * 100.0
    // Use the scrollPercentage as needed (e.g., update a label or send to analytics)
    print("Scroll Depth: \(scrollDepthPercentage)%")
    CCplugin.shared.scrollDepthPercentage = scrollDepthPercentage
  }
  func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    let contentHeight = scrollView.contentSize.height
    let scrollViewHeight = scrollView.bounds.height
    let scrollOffset = scrollView.contentOffset.y
    // Calculate the scroll percentage
    let scrollDepthPercentage = (scrollOffset / (contentHeight - scrollViewHeight)) * 100.0
    // Use the scrollPercentage as needed (e.g., update a label or send to analytics)
    print("Scroll Depth: \(scrollDepthPercentage)%")
    CCplugin.shared.scrollDepth = Int(scrollOffset)
    CCplugin.shared.scrollDepthPercentage = scrollDepthPercentage
  }
```

5. You need to set the pageLength for the paywall by accessing the pageLength property of the CCPlugin.shared instance and modifying its value.

```swift
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    debugPrint("pageLength:\(scrollView.contentSize.height)")
    CCplugin.shared.pageLength = Int(scrollView.contentSize.height)
  }
```

Enabling the debug mode:

*The debugMode property of the CCPlugin.shared instance can be set to true or false to enable or disable debug mode. When debug mode is enabled, toasts will be shown if the content ID or client ID entered is incorrect. This is useful for development purposes.*

```swift
CCplugin.shared.debugMode = false
```

</details>

<details>

<summary>Initialize the paywall</summary>

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following method on all the content/article pages.

```swift
CCplugin.shared.showPayWall(contentID: contentID,
           title: contentID,
           categories: ["category1","category2","category3"] ,
           sections: ["section12","section14"],
           tags: ["premium"],
           contentUrl: "https://www.google.com/",
           authorName: "abc",
           parentView: view,
           eventParamsDelegate: self,
           googleLogInDelegate: self,
           completiondelegate: self
    )                                    
```

</details>

| Parameters                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| contentID (string)            | This will be your article or content id for which detail needs to be checked.                                                                                                                                                                                                                                                                                                                                                       |
| parentView                    | Pass the view on which you are going to show your content.                                                                                                                                                                                                                                                                                                                                                                          |
| completionDelegate            | This will be used to handle the success and failure cases. Pass the class as the delegate where you want to handle success or failure. This delegate is of the protocol CCPluginCompletionHandlerDelegate, which has three methods: purchasedOrNot(), onPaywallVisible(paywallType, paywallDisplayType, paywallHeight), and onCustomLinkSlot(link, contentId) that will be triggered in case of success and failure of the process. |
| subscriberDelegate(optional)  | <p>This is an optional callback that will be called if you pass your class as its delegate. It will be triggered when the subscription button is tapped. If you don't pass it in your delegate, it will not show the subscription view.</p><p>subscriberDelegate, which has one method: subscribeBtnTap() which will be triggered whenever the user clicks the Subscribe Button.</p>                                                |
| signInDelegate(optional)      | <p>This is an optional callback that will be called if you pass your class as its delegate. It will be triggered when the sign-in button is tapped. If you don't pass it in your delegate, it will not show the sign-in view. </p><p>signInDelegate, which has one method: signInTap() that will be triggered when the user clicks the signin button.</p>                                                                           |
| eventParamsDelegate(optional) | This will be used to get the events params. Pass the class as the delegate where you want to handle success. This delegate is of the protocol CCPluginEventParamsDelegate, which has methods: success(**paywallId**: String, **contentId**: String, **paywallType**: String, **clientId**: String, **anonId**: String) that will be triggered in case of google login click.                                                        |
| googleLogInDelegate(optional) | This will be used to trigger your Google sign. This delegate is of the protocol CCPluginGoogleLogInDelegate, which has methods: startGoogleLogin() that will be triggered in case of google login click.                                                                                                                                                                                                                            |

> **Mandatory Step**
>
> * In your Project go to your target and in the URL types add a new one with URL schemes "conscent".
> * This is important to handle redirection or app launches from the browser.
> * call below function inside of `openURLContexts` scene delegate(inbuilt in iOS).

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FZDyQNWH7JXjMGat4Vr7n%2FImage%2018-04-24%20at%202.43%E2%80%AFPM.jpg?alt=media&amp;token=21bda580-45d3-4478-90c9-4026b83a13e7" alt=""><figcaption><p>Atached a screenshot for the reference:</p></figcaption></figure>

```swift
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let url = URLContexts.first?.url {
       CCplugin.shared.handleRelaunchApp(url: url)
    }
}
```

> You need to call **CCplugin.shared.exitSDK()** while leaving the scope of current controller.

```swift
override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)
    if parent == nil {
      // Back button action was triggered
      debugPrint("Back button pressed")
      CCplugin.shared.exitSDK()
    }
  }
```

**Call the below function and pass the userId, after the user has logged in:**

```swift
CCplugin.shared.setClientUserId(clientUserId: "Your_User_Id")
```

<details>

<summary>Login Functionality</summary>

Call this method to invoke our Login System

```swift
CCplugin.shared.onlyLoginFlow(  clientID: clientID, parentView: self.view)
```

</details>

<details>

<summary>Auto Login Functionality</summary>

The client can use his Login System using this functionality:&#x20;

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

* username: API Key -  present on conscent dashboard
* password: API Secret - present on conscent dashboard

```
ConscentBaseUrl:

SANDBOX: https://sandbox-api.conscent.in
PRODUCTION:  https://api.conscent.in
```

```swift
fileprivate func autoLogIn(emailMobile: String?) {
        // Define the API endpoint URL
        if let apiURL = URL(string: "\(ConscentBaseUrl)/api/v1/client/generate-temp-token") {
            // Create the request object
            var request = URLRequest(url: apiURL)
            request.httpMethod = "POST"
            
            // Define the request body parameters (if any)
            var parameters: [String: Any] = [:]
            if let input = emailMobile, !input.isEmpty {
                if input.contains("@") {
                    parameters["email"] = input
                } else {
                    parameters["phoneNumber"] = input
                }
            }

            do {
                let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
                request.httpBody = jsonData
                request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            } catch {
                print("Error creating JSON data: \(error)")
                return
            }
            
            // Set the Basic Authentication header
                let username = "J1EFAQR-H0N4921-QCXKVNH-6W9ZYY9"
                let password = "CFR472795Q42TTQJFV84M37A5G4SJ1EFAQRH0N4921QCXKVNH6W9ZYY9"
                if let data = "\(username):\(password)".data(using: .utf8) {
                    let base64Credentials = data.base64EncodedString()
                    let authString = "Basic \(base64Credentials)"
                    request.addValue(authString, forHTTPHeaderField: "Authorization")
                }

            // Create a URLSession instance
            let session = URLSession.shared

            // Create the data task
            let task = session.dataTask(with: request)
            { (data, response, error) in
                // Check for any errors
                if let error = error {
                    print("Error: \(error)")
                    return
                }
                
                // Ensure there is a valid HTTP response
                guard let httpResponse = response as? HTTPURLResponse else {
                    print("Invalid response")
                    return
                }
                
                // Check the response status code
                if httpResponse.statusCode == 201 {
                    // Successful request
                    if let responseData = data {
                        // Process the response data
                        let responseString = String(data: responseData, encoding: .utf8)
                        print("Response: \(responseString ?? "")")
                        do {
                            if let json = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: AnyObject] {
                                if let tempAuthToken = json["tempAuthToken"] as? String {
                                    CCplugin.shared.configure(mode: .stage, clientID: "6336e56f047afa7cb875739e")
                                    CCplugin.shared.debugMode = true
                                    DispatchQueue.main.async {
                                        if let input = emailMobile, !input.isEmpty {
                                            if input.contains("@") {
                                                CCplugin.shared.autoLogIn(contentID: "Client-Story-Id-1", clientID: "6336e56f047afa7cb875739e", token: tempAuthToken, email: input, parentView: self.view, autoLogInDelegate: self)
                                            } else {
                                                CCplugin.shared.autoLogIn(contentID: "Client-Story-Id-1", clientID: "6336e56f047afa7cb875739e", token: tempAuthToken, phone: input, parentView: self.view, autoLogInDelegate: self)
                                            }
                                        }
                                    }
                                }
                            }
                        } catch let error {
                            print(error)
                        }
                    }
                } else {
                    // Request failed
                    print("Request failed: \(httpResponse.statusCode)")
                }
            }

            // Start the data task
            task.resume()
        }
    }

```

**CCPluginAutoLogInDelegate:**

This will be used to handle the success and failure cases. Pass the class as the delegate where you want to handle success or failure.&#x20;

This delegate is of the protocol CCPluginAutoLogInDelegate, which has two methods:

&#x20;autoLogInsuccess() and autoLogInfailure() that will be triggered in case of success and failure of the process.<br>

**CCPluginUserDetailsDelegate:**

This delegate is of the protocol CCPluginUserDetailsDelegate, which has two methods:&#x20;

success() and failure() that will be triggered in case of success and failure of the process.

```swift
extension AccountViewController: CCPluginUserDetailsDelegate {
    func success(userDetails: String) {
        debugPrint(userDetails)
        if let jsonData = userDetails.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    // Use the `json` object
                    if let phoneNumber = json["phoneNumber"] as? String {
                        Helper.userName = phoneNumber
                    } else if let email = json["email"] as? String {
                        Helper.userName = email
                    }
                }
            } catch {
                print("Error converting data to JSON: \(error)")
            }
        }
    }
    
    func failure(error: String) {
        debugPrint(error)
    }
}
```

</details>

<details>

<summary>Logout Functionality</summary>

**CCPluginlogout:**

Pass the class as the delegate where you want to handle success or failure.&#x20;

This delegate is of the protocol CCPluginlogout, which has two methods:&#x20;

success() and failure() that will be triggered in case of success and failure of the process.

```swift
CCplugin.shared.getlogout(logoutBtnDelegate: self)
```

```swift
extension AccountViewController: CCPluginlogout {
    func succes(successData: String) {
        debugPrint(successData)
    }
    
    func fail(error: String) {
        debugPrint(error)
    }
}
```

</details>

### Demo APP [<mark style="color:orange;">Link</mark>](https://github.com/RoshanSharma8245/Demo-Blog-IOS)


# 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.

<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)


# Auto Login

AutoLogin is a functionality that enables you to use your Login system and get users validated at Conscent.ai System.

## A temporary token is generated using an API and this token needs to be stored at Client's end.

<mark style="color:green;">`POST`</mark> `{API_URL}/client/generate-temp-token`

**Authorization:**

Client API Key and API Secret must be passed in Authorization Headers using Basic Auth. With API Key as the Username and API Secret as the password.

#### Request Body

| Name                                          | Type   | Description              |
| --------------------------------------------- | ------ | ------------------------ |
| email<mark style="color:red;">\*</mark>       | String | email of the user        |
| phoneNumber<mark style="color:red;">\*</mark> | String | phone number of the user |
| clientId<mark style="color:red;">\*</mark>    | String | Client Id of the client  |

{% tabs %}
{% tab title="200: OK { "tempAuthToken": "644a2c13ce90df4882d1787a" }" %}

{% endtab %}
{% endtabs %}

> You need to pass either the phone number or email of the user from which they have made the purchase.

{% tabs %}
{% tab title="shell" %}

```sh
 csc('auto-login', {
      clientId: clientId,
      token: tokenEntered,
      phone: data?.phoneNumber,
      email: data?.email,
      successCallbackFunction: async (userDetailsObject: any) => {
        setShowLoginDetails(true);
        console.log('Success callback received from conscent auto Login', userDetailsObject);
        alert('login successfull');
      },
      errorCallbackFunction: (errorObject: any) => {
        console.error(errorObject);
        alert('login unsuccessfull');
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
```

{% endtab %}

{% tab title="javaScript" %}

```javascript
csc('auto-login', {
      clientId: clientId,
      token: tokenEntered,
      phone: data?.phoneNumber,
      email: data?.email,
      successCallbackFunction: async (userDetailsObject: any) => {
        setShowLoginDetails(true);
        console.log('Success callback received from conscent auto Login', userDetailsObject);
        alert('login successfull');
      },
      errorCallbackFunction: (errorObject: any) => {
        console.error(errorObject);
        alert('login unsuccessfull');
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
```

{% endtab %}

{% tab title="php" %}

```php
csc('auto-login', {
      clientId: clientId,
      token: tokenEntered,
      phone: data?.phoneNumber,
      email: data?.email,
      successCallbackFunction: async (userDetailsObject: any) => {
        setShowLoginDetails(true);
        console.log('Success callback received from conscent auto Login', userDetailsObject);
        alert('login successfull');
      },
      errorCallbackFunction: (errorObject: any) => {
        console.error(errorObject);
        alert('login unsuccessfull');
      },
      unauthorizedCallback: () => {
        console.log('unauthorized callback called');
      },
    });
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
ConscentWrapper.INSTANCE?.autoLogin(
                        phoneNumber = phoneNumber,
                        email = email,
                        clientActivity = this@LoginActivity,
                        tempToken = token
                    )
```

* The below code is a callback handler that gives a response in boolean format either **true** or **false**.
* **True** is defined as Login successful.
* **False** is defined as Login failed.

```kotlin
 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i(TAG, "RedirectionHandler.onActivityResult: ")
        if (resultCode == RESULT_OK) {
            Toast.makeText(applicationContext,"${data?.getStringExtra("STATUS")}",Toast.LENGTH_LONG).show()
        }
    }
```

{% endtab %}
{% endtabs %}


# Creating External Purchases

Creating purchases using Client's Login System:

**a.** This feature enables clients to integrate their login system, providing Conscent with only the user's unique user ID. Conscent will then optimize the user journey based on this information, enhancing the overall experience.

**b.** The client is responsible for managing the login and payment flow from their end, as Conscent does not have access to these details.

#### Steps to Enable External Purchase:

1. Navigate to global subscription settings on our dashboard \
   (**Visualise > Manage Subscriptions > Global Settings**)
2. Select ‘My Login’
3. Enter the redirect URL you want ConsCent to redirect the user to, along with the purchase token where you can handle the user’s purchase.

**Purchase Flow:**

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FvwUlMBSqEiH9Z0BKuMKC%2FUntitled%20Diagram.drawio.png?alt=media&amp;token=d921b947-016a-46bf-9e01-b2bd35187b21" alt=""><figcaption><p>Attached the screenshot for more clarity</p></figcaption></figure>

1. ConsCent redirects users from the <mark style="color:orange;">**Subscription Landing Page to your site**</mark> using the redirect URL set on the dashboard. The purchase token is passed as a query parameter during this redirection process.
2. Purchase information is transmitted to the client in the form of a JSON Web Token (JWT). Clients can easily extract and read purchase information from the JWT payload. The JWT is signed using the **RS256 algorithm** to ensure data integrity and authenticity.&#x20;

Additionally, clients can verify the **JWT using the public key provided by ConsCent.**

```
PUBLIC KEY:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTRnZkcSXEZ/PUSlJDCXf1SHGS
GKTc1CaT6/BqgXO6aSjC3QVZ1WKzeKhfhksy6iNHld9w0BLTfgHTCzKuFzvfa1tH
wfyyd+00wYSLBsGtQb1G+sO8o96yPASYe8thlnIN2jnFxZ+W9M+pb+h5pAuifIcS
XUjz4sZ6Y4lHhLLHvQIDAQAB
-----END PUBLIC KEY-----
```

3. After successfully charging the user for the purchase, the client must create a purchase record on ConsCent using the create external purchase API. This step ensures the synchronization of purchase data between our system and ConsCent's platform.

**Step 1: Creating the Token:**

You can create the JWT token by using our create-external-purcase-token API.&#x20;

Attached is the Postman collection file for using the APIs.

> <mark style="color:orange;">**Postman documentation can be found below:**</mark>

> [Conscent Sandbox Env.postman\_environment.json](https://file.notion.so/f/f/0580a633-2770-412f-b280-f17ac138548a/4408e758-a4ef-497a-b53b-b89a0d536b7b/ConsCent_Sandbox_Env.postman_environment.json?id=3165c5e7-b629-4c8d-85f6-72fffa20ab69\&table=block\&spaceId=0580a633-2770-412f-b280-f17ac138548a\&expirationTimestamp=1714053600000\&signature=eVk19CGvg5-1aWF_2DOYEyeoSgKW4SiNzJdtZs0JbdA\&downloadName=ConsCent+Sandbox+Env.postman_environment.json)
>
> [External Purchase APIs.postman\_environmen](https://file.notion.so/f/f/0580a633-2770-412f-b280-f17ac138548a/7faa2163-b4d9-42c5-8a76-5f0ce146a0db/External_Purchase_APIs.postman_collection.json?id=fe118beb-7ffb-4e28-a267-4b2097b4fa09\&table=block\&spaceId=0580a633-2770-412f-b280-f17ac138548a\&expirationTimestamp=1714053600000\&signature=1YTp8wdrp2tOqOQiQwj5pZr1v1LV6b6M6sYBPOIlirk\&downloadName=External+Purchase+APIs.postman_collection.json)[t.json](https://file.notion.so/f/f/0580a633-2770-412f-b280-f17ac138548a/7faa2163-b4d9-42c5-8a76-5f0ce146a0db/External_Purchase_APIs.postman_collection.json?id=fe118beb-7ffb-4e28-a267-4b2097b4fa09\&table=block\&spaceId=0580a633-2770-412f-b280-f17ac138548a\&expirationTimestamp=1714053600000\&signature=1YTp8wdrp2tOqOQiQwj5pZr1v1LV6b6M6sYBPOIlirk\&downloadName=External+Purchase+APIs.postman_collection.json)

{% hint style="info" %}
Replace the URLs based on the environment [(SANDBOX/PRODUCTION)](https://docs.conscent.ai/using-conscent.ai)
{% endhint %}

**Step 2: Verify the JWT in your system and complete the purchase.**

You may refer to <https://jwt.io/introduction>

**Step 3: Pass the token in the create-purchase API (postman collection attached above)**

**SAMPLE JWT Payload details:**

<table><thead><tr><th width="177">PARAMETER </th><th width="144">DATATYPE</th><th>DESCRIPTION</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>unique id assigned to each token to ensure consumability</td></tr><tr><td>iat</td><td>number</td><td>creation time in UTC timestamp format</td></tr><tr><td>subscriptionId</td><td>string</td><td>unique subscription ID for each subscription</td></tr><tr><td>tierId</td><td>string</td><td>unique tier ID for each subscription tier</td></tr><tr><td>amount</td><td>number</td><td>amount to be deducted to complete purchase</td></tr><tr><td>currency</td><td>string</td><td>currency in which amount is to be deducted</td></tr><tr><td>clientId</td><td>string</td><td>unique client ID for each client</td></tr><tr><td>consumeFreeTrial</td><td>boolean</td><td>Flag to avail of free trial</td></tr><tr><td>couponCode</td><td>string</td><td>coupon code applied by the user</td></tr><tr><td>ipAddress</td><td>string</td><td>IP address of the user</td></tr><tr><td>userAgent</td><td>string</td><td>user agent of the user</td></tr></tbody></table>


# Landing Page API

The landing page API enables clients to utilize their Subscription Landing Page and can be used to power subscription plans through Conscent.

> Create the subscription plans and landing pages on the Cosncent Dashboard before implementing the Landing Page API.

<mark style="color:green;">`GET{API_URL}`</mark><mark style="background-color:yellow;">/subscription/campaign?pathURL=Netflix\&clientId=5f92a62013332e0f667794dc</mark>

**PARAMS**

| Name     | Value                                                                                         |
| -------- | --------------------------------------------------------------------------------------------- |
| pathURL  | Same as the one present in Visualise ->  Subscriptions -> Landing Page -> CampaignURL         |
| clientId | [ClientId](https://sandbox-client.conscent.in/client/dashboard/Documentation) on th dashboard |

**Response**

{% tabs %}
{% tab title="200" %}

<pre class="language-json"><code class="lang-json"><strong>{
</strong>    "message": "Got landing page with the provided path",
    "isCampaignActive": true,
    "faviconUrl": "",
    "useClientFlow": false,
    "clientCampaignDetails": {
        "landingPage": {
            "customization": {
                "primaryColor": "#000000",
                "secondaryColor": "#d3ca6f",
                "buttonColor": "#000000",
                "buttonTextColor": "#f3fbf7",
                "priceTextColor": "#000000"
            },
            "title": "Test Subs123",
            "description": "Get access to world of quality content.",
            "headerRedirectUrl": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client-Story-Id-1",
            "desktopBannerUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Demo%20Client/banners/Demo%20Client%20-%20desktopBanner-f5a777.png",
            "mobileBannerUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Outlook/banners/Outlook%20-%20mobileBanner-4785ee.png",
            "brandLogoUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Demo%20Client/banners/Demo%20Client%20-%20brandLogo-d32f8b.png",
            "deletedAt": null,
            "_id": "6267f6b5a2d25f456bc69bc2",
            "clientId": "5f92a62013332e0f667794dc",
            "template": "t1",
            "createdAt": "2022-04-26T13:42:13.449Z",
            "updatedAt": "2023-12-01T12:13:02.429Z",
            "__v": 243
        },
        "subscriptions": [
            {
                "freeTrial": {
                    "enabled": false,
                    "duration": null
                },
                "benefits": "Benefit1,Benefit2,Benefit3", // Subscription benefits.
                "physical": false,
                "digital": true,
                "adFree": false,
                "migrated": false,
                "couponsEnabled": true,
                "adminCoupon": "",
                "usedCouponNumbers": [],
                "deletedAt": null,
                "_id": "61e93279bf6de47e4f6a676b",
                "recommended": false,
                "enabled": true,
                "clientId": "5f92a62013332e0f667794dc",
                "title": "Didi+Phy+Ad Free", // Title of the subscription
                "tiers": [
                    {
                        "priceOverrides": {
                            "country": []
                        },
                        "currency": "INR", // Currency of the user's country will be present here.
                        "basePrice": 0, // Base price which has been set in the client dashboard.
                        "offers": [
                            {
                                "_id": "617a703504ab353a12d84d2a",
                                "title": "IDFC Bank1",
                                "benefits": "This is the first benefit This is the first benefit This is the first benefit This is the first benefit This is the first benefit This is the first benefit ",
                                "iconUrl": "https://storage.googleapis.com/bkt-conscent-public-stage/Outlook/offers/617a703504ab353a12d84d2a-2f1c03.png"
                            }
                        ],
                        "_id": "61e93279bf6de47e4f6a676d",
                        "price": 6969, // Amount of the subscription
                        "duration": 12 // Duration in months
                    }
                ],
                "iconUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Outlook/subscriptions/61e93279bf6de47e4f6a676b-a6e1b9.png",
                "createdAt": "2022-01-20T09:59:22.673Z",
                "updatedAt": "2023-12-01T12:15:39.739Z",
                "__v": 22,
                "currencySymbol": "₹" // Currency symbol will change according to the currency.
            }
        ],
        "recommendedSub": ""
    },
    "clientId": "5f92a62013332e0f667794dc"
}
</code></pre>

{% endtab %}
{% endtabs %}


# Login Screen Customization

Conscent.ai makes it effortless to handle the login settings and customization from the dashboard itself.

The user can log in in four ways:

* Mobile Number
* Email Address
* Google Login
* Facebook Login

Attaching the [link](https://client.conscent.in/client/dashboard/login-setting) that will be redirected to the login customization page.

## [Login Page Settings](https://client.conscent.in/client/dashboard/login-setting)

<div align="center"><figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2Fj5MF8uRM81Kd7xDSGm9Z%2FScreenshot%202023-06-02%20at%206.59.19%20PM.png?alt=media&amp;token=6e895e74-745b-4924-aa0a-85b9602d4c90" alt=""><figcaption><p>Login Page Settings</p></figcaption></figure></div>

### [Customize your Login Screen](https://client.conscent.in/client/dashboard/login-setting)

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FEjrMeyQUs0JJFyR3tqy6%2FScreenshot%202023-06-02%20at%206.38.46%20PM.png?alt=media&amp;token=4471806b-eed4-48be-9826-e16346827575" alt=""><figcaption><p>Login Screen</p></figcaption></figure>

### [Customize your OTP Screen](https://client.conscent.in/client/dashboard/login-setting)

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FjQmBYd9BWaxPbghnfAEA%2FScreenshot%202023-06-02%20at%206.38.30%20PM.png?alt=media&amp;token=a740ac65-18f0-4bec-a3aa-40449331fbda" alt=""><figcaption><p>OTP Screen</p></figcaption></figure>


# Integrating Client Payment Gateway

Conscent offers a straightforward method to configure your payment gateway directly from the dashboard.

**Steps to integrate the payment gateway:**

**a.** Visit the [Monetise Section ](https://client.conscent.in/client/dashboard/payment-gateway)on Conscent Dashboard

**b.** Navigate to the Payment Gateway tab.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FYquA5x9ZxryUIwUUUxTY%2FScreenshot%202023-10-26%20at%2012.05.32%20PM.png?alt=media&amp;token=044b0d06-3a7b-4bb0-aa75-d1922c8ed11f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FN58up40uTBP23uXAwSCA%2FScreenshot%202023-10-26%20at%2012.05.16%20PM.png?alt=media&amp;token=ba02c6c8-b446-477e-a7a3-8af78cd14bc0" alt="" width="375"><figcaption></figcaption></figure>

**c.** Click on Add Gateway and enter your *Razorpay* credentials i.e. Key ID and Key Secret, and an alias name. Then Save and Continue

> **Note:** Key Secret will not be physically displayed on the dashboard for security reasons.

**d.** After saving, you'll need to enter the generated webhook URL and secret in your webhook section on the Razorpay dashboard.

### Domain Whitelisting and Razorpay Configuration Guide (For Production):

<mark style="color:orange;">**Step 1: Whitelist Your Domain**</mark>

To set up your domain for payments, start by creating a CNAME record pointing to the new payment gateway.

**Instructions:**

**1. Access DNS Management:**

* Log in to the control panel of your domain registrar or DNS hosting provider.

**2. Create a CNAME Record:**

* Host/Name/Alias: Enter payment (e.g., this will create payment.clientname.com).
* Type: CNAME
* Value/Points to: payment-v2.netlify.app

**3. Save Changes:**

* Confirm and save the new CNAME record.
* Note that DNS changes may take up to 24-48 hours to propagate.

<mark style="color:orange;">**Step 2: Configure Razorpay Settings**</mark>

Once the CNAME is active, update your Razorpay account to recognize your new subdomain.

**Instructions:**

1. **Log in to Razorpay Dashboard:**

* Go to [dashboard.razorpay.com](https://dashboard.razorpay.com/) and log in.

2. **Navigate to Account Settings:**

* Click your profile icon in the top-right corner.
* Select **“Account & Settings”** from the dropdown.

3. **Update Business Website Details:**

* In the “Business Website Details” section, update your domain to *<mark style="color:blue;">payment.clientname.com.</mark>*

4. **Save Changes:**

* Click “Save” or “Update” to apply your new settings.

<mark style="color:orange;">**Step 3: Configure Razorpay for One-Time and Recurring Transactions**</mark>

Enable and test payment modes for one-time and recurring transactions on your Razorpay account.

**Instructions:**

1. **Enable Payment Modes:**

* Go to “Settings” > “Payment Methods” on the Razorpay dashboard.
* Enable all relevant payment methods (Credit Card, Debit Card, Net Banking, etc.).

2. **Set Up Recurring Payments:**

* Under “Payments”, navigate to “Subscriptions” and click “Enable Recurring Payments.”
* Follow any on-screen instructions to complete the setup.

3. **Test Payment Flow:**

* Use Razorpay’s test mode to conduct test transactions for both one-time and recurring payments to ensure smooth functionality.


# Integrating with APIs

Achieving the desired custom-tailored use-case by calling Conscent.ai APIs and coding out the logic at your end...

Here are the APIs in this section:

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td>User Details and Subscriptions Information</td><td></td><td></td><td><a href="/integrating-with-apis/user-details-and-subscriptions-information">User Details and Subscriptions Information</a></td></tr><tr><td>Purchased Subscriptions</td><td></td><td></td><td><a href="/integrating-with-apis/purchased-subscriptions">Purchased Subscriptions</a></td></tr><tr><td>User and Purchase Details</td><td></td><td></td><td><a href="/integrating-with-apis/user-and-purchase-details">User and Purchase Details</a></td></tr><tr><td>Client Purchases</td><td></td><td></td><td><a href="/integrating-with-apis/client-purchases">Client Purchases</a></td></tr><tr><td>Client Micropayments</td><td></td><td></td><td><a href="/integrating-with-apis/client-micropayments">Client Micropayments</a></td></tr><tr><td>Client Passes</td><td></td><td></td><td><a href="/integrating-with-apis/client-passes">Client Passes</a></td></tr><tr><td>Cancel Active Subscriptions</td><td></td><td></td><td><a href="/integrating-with-apis/cancel-active-subscriptions">Cancel Active Subscriptions</a></td></tr></tbody></table>


# User Details and Subscriptions Information

## Get the user Details and subscriptions that were purchased.

<mark style="color:blue;">`GET`</mark> `{API_URL}/user/user-and-subscription-details`

Auth required: NO

#### Query Parameters

| Name                                          | Type   | Description              |
| --------------------------------------------- | ------ | ------------------------ |
| clientId                                      | String | client id of the client  |
| userId                                        | String | user id of the user      |
| email<mark style="color:red;">\*</mark>       | String | email of the user        |
| phoneNumber<mark style="color:red;">\*</mark> | String | phone number of the user |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which hw has made the purcahse.

```json
{
    "userdetails": {
        "name": "AKHIL",
        "email": "testmail51@gmail.com",
        "secondaryPhoneNumber": "9832748888",
        "secondaryEmail": "",
        "dateOfBirth": "1999-01-01T09:50:21.951Z",
        "address": {
            "apartment": "ouy",
            "area": "029384kdsjf",
            "pincode": "530009",
            "landmark": "fj",
            "city": "8732489",
            "state": "",
            "country": "IN"
        },
        "country": "IN",
        "promotionalOptIn": true,
        "lastPurchasedOn": "2022-03-08T11:37:31.667Z",
        "wallet": {
            "balance": {
                "$numberDecimal": "50.00"
            },
            "currency": "INR"
        }
    },
    "userSubscriptions": [
        {
            "_id": "62273ffbd5c69afcd7c05349",
            "client": "Outlook",
            "price": 1000,
            "purchasedOn": "2022-03-08T11:37:31.537Z",
            "subscriptionTitle": "Subscription test physical",
            "expiryDate": "2022-04-08T11:37:31.518Z",
						"partialAccess": false,
            "sectionsInclude": [],
            "authorsInclude": [],
            "sectionsExclude": [],
            "authorsExclude": [],
            "tagsInclude": [],
            "tagsExclude": [],
            "subscriptionType": {
                "physical": true,
                "digital": false,
                "adFree": false
            },
            "benefits": "Easy access to contents",
            "logoUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/stage/Outlook/banners/Outlook%20-%20brandLogo",
            "rzpSubscriptionId": "sub_J4a4NYpUc0qDMU",
            "status": "ACTIVE",
            "freeTrial": false,
            "tierId": "61a49984fabe8d7705a2cabd",
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            },
            "subscriptionDurationInMonths": 1,
            "subscriptionPriceInInr": 1000,
            "allowCancellation": true,
            "cancellationUrl": "http://localhost:3000/consumption?subscription=62273ffbd5c69afcd7c05349",
            "allowRenewal": false,
            "renewalUrl": ""
        }
    ]
}
```


# Purchased Subscriptions

## Get the details of previously purchased subscriptions.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/purchases/subscriptions`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name        | Type          | Description              |
| ----------- | ------------- | ------------------------ |
| userId      | String        | user id of the user      |
| from        | ISODateString |                          |
| to          | ISODateString |                          |
| phoneNumber | String        | phone number of the user |
| email       | String        | email of the user        |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which hw has made the purcahse.

```json
{
  "purchases": [
    {
      "manuallyRenewed": false,
      "renewSubscription": false,
      "availedOffers": ["617ba48ec3b5066393988f22"],
      "promotional": false,
      "categories": [],
      "freeTrial": false,
      "migrated": false,
      "clientId": "5f92a62013332e0f667794dc",
      "clientContentId": "Client Story Id 1",
      "contentId": "5fbe46efbee15f1cebc81515",
      "buyingPrice": 100.36,
      "price": 104,
			"partialAccess": false,
      "sectionsInclude": [],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [],
      "tagsExclude": [],
      "priceDetails": {
        "price": 104,
        "currency": "INR"
      },
      "subscriptionDetails": {
        "inrPrice": 104,
        "duration": 1
      },
      "expiryDate": "2022-03-28T12:49:02.844Z",
      "subscriptionId": "61a49855fabe8d7705a2cab4",
      "tierId": "61a49855fabe8d7705a2cab6",
      "createdAt": "2022-03-03T09:13:53.266Z",
      "userId": "613720ec6a14e1100bdfb9f5",
      "userEmail": "asdf@sdf.co",
      "userPhoneNumber": "129347792",
      "userName": "asdf",
      "userAddress": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "clientSpecificUserId": "234234612"
    },
    {
      "manuallyRenewed": false,
      "renewSubscription": false,
      "availedOffers": [],
      "promotional": false,
      "categories": [],
			"partialAccess": false,
      "sectionsInclude": [],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [],
      "tagsExclude": [],
      "freeTrial": false,
      "migrated": false,
      "clientId": "5f92a62013332e0f667794dc",
      "clientContentId": "Client Story Id 1",
      "contentId": "5fbe46efbee15f1cebc81515",
      "buyingPrice": 193.97,
      "price": 201,
      "priceDetails": {
        "price": 201,
        "currency": "INR"
      },
      "subscriptionDetails": {
        "inrPrice": 201,
        "duration": 2
      },
      "expiryDate": "2022-04-25T08:00:12.714Z",
      "subscriptionId": "617a718d04ab353a12d84d30",
      "tierId": "6180db518634ae0b03c136b5",
      "userId": "5fca03a52185f150382ff144",
      "userEmail": "test+stagetest@test.com",
      "userPhoneNumber": "9999999999",
      "userName": "test name",
      "userAddress": {
        "apartment": "India",
        "area": "India",
        "pincode": "123423",
        "landmark": "India",
        "city": "test",
        "state": "ANDHRA PRADESH",
        "country": "IN"
      },
      "clientSpecificUserId": "234234612"
    }
  ],
  "paginationInfo": {
    "pageNumber": 1,
    "pageSize": 2,
    "recordsReturned": 2
  }
}
```


# User and Purchase Details

## Get the user Details and subscriptions.

<mark style="color:blue;">`GET`</mark> `{API_URL}/user/user-and-purchase-details`

Auth required: NO

#### Query Parameters

| Name        | Type          | Description              |
| ----------- | ------------- | ------------------------ |
| userId      | String        | user id of the user      |
| email       | String        | email of the user        |
| phoneNumber | String        | phone number of the user |
| from        | ISODateString |                          |
| to          | ISODateString |                          |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which hw has made the purcahse.

```json
{
    "userdetails": {
        "name": "Pushpankar",
        "phoneNumber": "9936225088",
        "secondaryEmail": "skdfjn@jnadf.com",
        "address": {
            "apartment": "Flat",
            "area": "Area",
            "pincode": "Zip",
            "landmark": "",
            "city": "City",
            "state": "ANDAMAN & NICOBAR ISLANDS",
            "country": "IN"
        },
        "country": "IN",
        "promotionalOptIn": true,
        "lastPurchasedOn": "2023-04-17T14:01:00.411Z",
        "wallet": {
            "balance": {
                "$numberDecimal": "0.00"
            },
            "currency": "INR"
        }
    },
    "userSubscriptions": [
        {
            "_id": "63b2b8b938dcac1e9a1d55c6",
            "client": "Demo Client",
            "price": 400,
            "gst": 61.01711999999999,
            "purchasedOn": "2023-01-02T10:58:01.603Z",
            "subscriptionTitle": "Digital",
            "expiryDate": "2023-02-02T10:58:01.600Z",
            "subscriptionType": {
                "physical": false,
                "digital": true,
                "adFree": false
            },
        "partialAccess": false,
	 "sectionsInclude": [],
	 "authorsInclude": [],
	 "sectionsExclude": [],
	 "authorsExclude": [],
	 "tagsInclude": [],
	 "tagsExclude": [],
            "benefits": "It's very good,Very Helpful,Good to read,Good content,50% OFF, 100% OFF",
            "logoUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/Static+Assets/Outlook-Logo.png\n",
            "freeTrial": false,
            "tierId": "6347b644bff071350cfd0f55",
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            },
            "subscriptionDurationInMonths": 1,
            "subscriptionPriceInInr": 400,
            "allowCancellation": false,
            "cancellationUrl": "",
            "allowRenewal": true,
            "renewalUrl": "https://dashboards.tsbdev.co/dashboard/consumption?subscription=63b2b8b938dcac1e9a1d55c6"
        },
        {
            "_id": "637f9be1837ec364a7fa1683",
            "client": "Demo Client",
            "price": 49,
            "gst": 7.4745972,
            "purchasedOn": "2022-11-24T16:29:21.159Z",
            "subscriptionTitle": "AD Free-Lite",
            "expiryDate": "2022-12-24T16:29:21.153Z",
            "subscriptionType": {
                "physical": false,
                "digital": false,
                "adFree": true
            },
						"partialAccess": false,
			      "sectionsInclude": [],
			      "authorsInclude": [],
			      "sectionsExclude": [],
			      "authorsExclude": [],
			      "tagsInclude": [],
			      "tagsExclude": [],
            "benefits": "Ad-free experience, Digital Access, Premium Content",
            "logoUrl": "https://conscent-public.s3.ap-south-1.amazonaws.com/Static+Assets/Outlook-Logo.png\n",
            "freeTrial": false,
            "tierId": "61e951161a563d0729652d23",
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            },
            "subscriptionDurationInMonths": 1,
            "subscriptionPriceInInr": 49,
            "allowCancellation": false,
            "cancellationUrl": "",
            "allowRenewal": true,
            "renewalUrl": "https://dashboards.tsbdev.co/dashboard/consumption?subscription=637f9be1837ec364a7fa1683"
        }
    ],
    "passes": [
        {
            "_id": "637c710d7153ef201cd8be8f",
            "client": "Demo Client",
            "price": 78,
            "gst": 11.898338399999998,
            "purchasedOn": "2022-11-22T06:49:49.989Z",
            "expiryDate": "2022-11-22T13:49:49.968Z",
            "freeTrial": false,
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            }
        }
    ],
    "payPerUses": [
        {
            "_id": "643d511c0dfb996ad37a0f1c",
            "client": "Demo Client",
            "price": 10,
            "gst": 1.525428,
            "purchasedOn": "2023-04-17T14:01:00.377Z",
            "expiryDate": "2023-04-24T14:01:00.350Z",
            "freeTrial": false,
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            }
        },
        {
            "_id": "642bbb2b5a3e9b1441cbb058",
            "client": "Demo Client",
            "price": 9999,
            "gst": 1525.2754572,
            "purchasedOn": "2023-04-04T05:52:43.823Z",
            "expiryDate": "2023-04-06T05:52:43.810Z",
            "freeTrial": false,
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            }
        },
        {
            "_id": "64103ec1644c430727a2b654",
            "client": "Demo Client",
            "price": 10,
            "gst": 1.525428,
            "purchasedOn": "2023-03-14T09:30:41.364Z",
            "expiryDate": "2023-03-16T09:30:41.345Z",
            "freeTrial": false,
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            }
        },
        {
            "_id": "637f9b78837ec364a7fa151c",
            "client": "Demo Client",
            "price": 16,
            "gst": 2.4406848,
            "purchasedOn": "2022-11-24T16:27:36.304Z",
            "expiryDate": "2022-11-26T16:27:36.294Z",
            "freeTrial": false,
            "clientId": "5f92a62013332e0f667794dc",
            "gstComponents": {
                "physical": 0,
                "digital": 0
            }
        }
    ]
}
```


# Client Purchases

## Get the details of the purchases.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/purchases`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint

#### Query Parameters

| Name        | Type          | Description              |
| ----------- | ------------- | ------------------------ |
| userId      | String        | user id of the user      |
| email       | String        | email of the user        |
| phoneNumber | String        | phone number of the user |
| from        | ISODateString |                          |
| to          | ISODateString |                          |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which hw has made the purcahse.

```json
{
    "transactionDetails": [
        {
            "promotional": false,
            "_id": "643e49dc2309ab30bc00ccf2",
            "userAccount": {
                "phoneNumber": "8712334265",
                "email": "bnnnn@gmail.com"
            },
            "clientId": {
                "name": "Demo Client"
            },
            "contentId": {
                "title": "Client-Story Id 1",
                "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client-Story-Id-1"
            },
            "buyingPrice": 319.21,
            "price": 399,
            "type": "PASS",
            "createdAt": "2023-04-18T07:42:20.749Z"
        }
    ],
    "pagination": {
        "pageNumber": 1,
        "pageSize": 10,
        "totalRecords": 1,
        "totalPages": 1
    }
}
```


# Client Micropayments

## Get the details of the micro-payments.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/purchases/micropayments`

Auth required: YES

Please pass your API key as the username and API secret as the password as Basic Auth to access the endpoint.

#### Query Parameters

| Name        | Type          | Description              |
| ----------- | ------------- | ------------------------ |
| userId      | String        | user id of the user      |
| email       | String        | email of the user        |
| phoneNumber | String        | phone number of the user |
| from        | ISODateString |                          |
| to          | ISODateString |                          |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which hw has made the purcahse.

```json
{
    "purchases": [
        {
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": false,
            "migrated": false,
            "clientId": "5f92a62013332e0f667794dc",
            "clientContentId": "Client-Story-Id-1",
            "contentId": "61fba4adcbcaaf727a00168d",
            "buyingPrice": 8,
            "price": 10,
            "priceDetails": {
                "price": 10,
                "currency": "INR"
            },
            "expiryDate": "2023-04-15T10:22:57.494Z",
            "createdAt": "2023-04-13T10:22:57.507Z",
            "userId": "6346608680c2216fe33d84fa",
            "userEmail": "bnnnn@gmail.com",
            "userPhoneNumber": "8750314176",
            "userName": "Kajal",
            "userAddress": {
                "apartment": "ggghhh",
                "area": "kkkkkhhh",
                "pincode": "922111",
                "landmark": "sasshhh",
                "city": "jjjjjhhh",
                "state": "ffffffhhh",
                "country": "iiiiihhh"
            }
        },
        {
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": false,
            "migrated": false,
            "clientId": "5f92a62013332e0f667794dc",
            "clientContentId": "Client-Story-Id-3",
            "contentId": "620b94557bef8873d93bf32b",
            "buyingPrice": 8,
            "price": 10,
            "priceDetails": {
                "price": 10,
                "currency": "INR"
            },
            "expiryDate": "2023-03-26T06:58:54.416Z",
            "createdAt": "2023-03-16T06:58:54.434Z",
            "userId": "6346608680c2216fe33d84fa",
            "userEmail": "bnnnn@gmail.com",
            "userPhoneNumber": "8750334265",
            "userName": "Kajal",
            "userAddress": {
                "apartment": "ggghhh",
                "area": "kkkkkhhh",
                "pincode": "922111",
                "landmark": "sasshhh",
                "city": "jjjjjhhh",
                "state": "ffffffhhh",
                "country": "iiiiihhh"
            }
        },
        {
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": false,
            "migrated": false,
            "clientId": "5f92a62013332e0f667794dc",
            "clientContentId": "Client-Story-Id-1",
            "contentId": "61fba4adcbcaaf727a00168d",
            "buyingPrice": 16,
            "price": 20,
            "priceDetails": {
                "price": 20,
                "currency": "INR"
            },
            "expiryDate": "2023-02-11T07:39:49.821Z",
            "createdAt": "2023-02-09T07:39:49.856Z",
            "userId": "6346608680c2216fe33d84fa",
            "userEmail": "bnnnn@gmail.com",
            "userPhoneNumber": "8750334265",
            "userName": "Kajal",
            "userAddress": {
                "apartment": "ggghhh",
                "area": "kkkkkhhh",
                "pincode": "922111",
                "landmark": "sasshhh",
                "city": "jjjjjhhh",
                "state": "ffffffhhh",
                "country": "iiiiihhh"
            }
        }
    ],
    "paginationInfo": {
        "pageNumber": 1,
        "pageSize": 3,
        "recordsReturned": 3
    }
}

```


# Client Passes

## Get the details of the passes.

<mark style="color:blue;">`GET`</mark> `{API_URL}/client/purchases/passes`

Auth required: YES

Please pass your API key as the username and API secret as password as Basic Auth to access the endpoint.

#### Query Parameters

| Name        | Type          | Description              |
| ----------- | ------------- | ------------------------ |
| userId      | String        | user id of the user      |
| email       | String        | email of the user        |
| from        | ISODateString |                          |
| to          | ISODateString |                          |
| phoneNumber | String        | phone number of the user |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

> You need to pass either phone number or email of the user from which hw has made the purcahse.

```json

{
    "purchases": [
        {
            "availedOffers": [],
            "promotional": false,
            "categories": [],
            "freeTrial": false,
            "migrated": false,
            "clientId": "5f92a62013332e0f667794dc",
            "clientContentId": "Client-Story-Id-1",
            "contentId": "61fba4adcbcaaf727a00168d",
            "buyingPrice": 319.21,
            "price": 399,
            "priceDetails": {
                "price": 399,
                "currency": "INR"
            },
            "expiryDate": "2023-04-18T14:42:20.741Z",
            "createdAt": "2023-04-18T07:42:20.749Z",
            "userId": "6346608680c2216fe33d84fa",
            "userEmail": "bnnnn@gmail.com",
            "userPhoneNumber": "8243334265",
            "userName": "Kajal",
            "userAddress": {
                "apartment": "ggghhh",
                "area": "kkkkkhhh",
                "pincode": "922111",
                "landmark": "sasshhh",
                "city": "jjjjjhhh",
                "state": "ffffffhhh",
                "country": "iiiiihhh"
            }
        }
    ],
    "paginationInfo": {
        "pageNumber": 1,
        "pageSize": 2,
        "recordsReturned": 1
    }
}
```


# Cancel Active Subscriptions

## The client can cancel the active subscriptions for a user

<mark style="color:green;">`POST`</mark> `{API_URL}/client/cancel-subscriptions/{userId}`

Auth required: YES

Please pass your API key as the username and API secret as the password as basic auth to access the endpoint.

{% tabs %}
{% tab title="200: OK " %}
{ "message": "Subscriptions Cancelled Successfully" }
{% endtab %}
{% endtabs %}

```json
{
    "userAccountId": "6242c8f195dcaf49ddc9afbd",
    "purchases": [
        {
            "id": "65dd8927ae60c411df51b902",
            "subscriptionId": "6188d151e018990cee9630ad",
            "tierId": "6188d151e018990cee9630af",
            "subscriptionDetails": {
                "duration": 1,
                "inrPrice": 999
            },
            "subscriptionType": {
                "physical": false,
                "digital": true,
                "adFree": false
            },
	    "price": 999,
	    "priceDetails": {
	    "currency": "INR",
	    "price": 999
		}}
    ],
    "message": "Subscriptions Cancelled Successfully"
}
```


# Delete User

## The client can cancel the active subscriptions for a user

<mark style="color:green;">`DELETE`</mark> `{API_URL}/client/delete-user?userId=6764322345768765998778`

Auth required: YES

Please pass your API key as the username and API secret as the password as basic auth to access the endpoint. (Pick this from Conscent Dashboard)

{% hint style="info" %}
The userId will be of Conscent (Pick this from local storage)
{% endhint %}

| Parameter | Description                     |
| --------- | ------------------------------- |
| userId    | Unique Id assigned to each user |

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "message": "User Deleted Successfully.",
    "data": {
        "email": "671a2abe671706f42753f892@deleted.deleted",
        "phoneNumber": "671a2abe671706f42753f892PhoneDeleted"
    }
}
```

{% endtab %}
{% endtabs %}


# Events API Docs

The Event Collection API enables users to track and record events via a simple HTTP POST request to /collect/event endpoint. This facilitates insights into user interactions and behavior for analytics

### Base URL

The base URL for making requests to the Event Collection API is:

| SANDBOX                                                                                                             | PRODUCTION                                                                                            |
| ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| [<mark style="color:orange;">https://sandbox-collection.conscent.in</mark>](https://sandbox-collection.conscent.in) | [<mark style="color:orange;">https://collections.conscent.in</mark>](https://collections.conscent.in) |

<details>

<summary>API Endpoints:</summary>

**Endpoint:** `/collect/event`

**Method:** POST

**Description:** The `/collect/event` endpoint is used to collect and store events in the system. Clients can send event data as JSON in the request body. The server will process the incoming event data and store it for further analysis.

**Request Body:**

The request body must contain a JSON object representing the event data. The JSON object can include the following properties:

* <mark style="color:orange;">**`messageBody`**</mark> (\[Event], required): An array containing one or more event objects, each representing an individual event.
* <mark style="color:orange;">**`messageheader`**</mark> (Object, optional): A key-value pair object containing additional headers for the event collection.

```
* Example Request: (HTTP request RAW) *

POST /collect/event HTTP/1.1
Host: example.com
Content-Type: application/json
{
  "messageBody": 
  [
		{
			...properties
		},
		{
			...properties
		}
  ],
  "messageHeaders": 
	        {
		        ...headers
	        }
}
```

**Response:**

* Status Code: 201 OK
* Content-Type: application/json

Example Response:

```json
[
	{
		"headers": {},
		"value": "{\"pingId\": \"c523aa41-9f0f-4fc2-bc96-5a8ff5520b78\"}" 
	}
]
```

</details>

<details>

<summary><strong>Error Handling:</strong></summary>

If there's an issue with the request or the server cannot process the event data, an appropriate error response will be returned.

**Example Error Response:**

```json
{
  "error": "Bad Request",
  "message": "invalid event type",
	"statusCode": 400
}
```

</details>

**Error Codes:**

The API may return various HTTP status codes to indicate the success or failure of a request. Here are some of the common status codes:

<table><thead><tr><th width="240">ERROR CODE</th><th>DESCRIPTION</th></tr></thead><tbody><tr><td><mark style="color:orange;">201 OK</mark></td><td>The request was successful, and the event data was collected.</td></tr><tr><td><mark style="color:orange;">400 Bad Request</mark></td><td>The request was malformed or had invalid parameters.</td></tr><tr><td><mark style="color:orange;">429 Too Many Requests</mark></td><td>The client has exceeded the rate limit for the /collect/event endpoint.</td></tr><tr><td><mark style="color:orange;">500 Internal Server Error</mark></td><td>An unexpected server error occurred.</td></tr></tbody></table>

<details>

<summary><strong>Rate Limits:</strong></summary>

To maintain fair usage and prevent abuse, rate limits are imposed on the /collect/event endpoint. If a client surpasses the permitted number of requests within a specific time window, the API will respond with a rate-limiting error.

**Example Response Headers:**

```
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1672766785
```

</details>

**Rate Limit Headers:**

<table><thead><tr><th width="229">Rate Limit Name</th><th>Description </th></tr></thead><tbody><tr><td><mark style="color:orange;">X-RateLimit-Limit</mark></td><td>The maximum number of requests allowed within the current time window.</td></tr><tr><td><mark style="color:orange;">X-RateLimit-Remaining</mark></td><td>The number of remaining requests allowed within the current time window.</td></tr><tr><td><mark style="color:orange;">X-RateLimit-Reset</mark></td><td>The time at which the rate limit will be reset (usually in UTC timestamp).</td></tr></tbody></table>


# Different Types of Events

The mentioned events, each designed with unique functionalities and specific properties, are passed as objects in the messageBody for individual event captures, ensuring effective analytics.

1. **PING:** It's a periodic event triggered every 15 seconds while the user is on a page.

<table><thead><tr><th>PARAMETERS</th><th width="129">DATATYPE</th><th width="285">DESCRIPTION</th><th>TYPE<select><option value="45ff5e1dcd8c4062aa035ea1c3a6d873" label="REQUIRED" color="blue"></option><option value="78dad05c4d92408789c081a5fee74437" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="45ff5e1dcd8c4062aa035ea1c3a6d873">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>PING</strong></mark></td><td><span data-option="45ff5e1dcd8c4062aa035ea1c3a6d873">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="45ff5e1dcd8c4062aa035ea1c3a6d873">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="45ff5e1dcd8c4062aa035ea1c3a6d873">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">pingId</mark></td><td>uuid</td><td>A unique pingId for each session.</td><td><span data-option="45ff5e1dcd8c4062aa035ea1c3a6d873">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">active</mark></td><td>int8</td><td><p>0 when the user is out of focus.</p><p>1 when the user is in focus.</p></td><td><span data-option="45ff5e1dcd8c4062aa035ea1c3a6d873">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique user ID for each user if he/she/they is logged in</td><td><span data-option="78dad05c4d92408789c081a5fee74437">OPTIONAL</span></td></tr></tbody></table>

2. **CLICK:** It's an event triggered when the user clicks a subject of interest.

<table><thead><tr><th width="152">PARAMETERS</th><th width="111">DATATYPE</th><th width="312">DESCRIPTION</th><th>TYPE<select><option value="d725a0406db3469eb2c1da514959d768" label="REQUIRED" color="blue"></option><option value="35e68f1a1c474ab09399b9185e114dbc" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="d725a0406db3469eb2c1da514959d768">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>CLICK</strong></mark></td><td><span data-option="d725a0406db3469eb2c1da514959d768">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="d725a0406db3469eb2c1da514959d768">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="d725a0406db3469eb2c1da514959d768">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique user ID for each user if he/she is logged in</td><td><span data-option="35e68f1a1c474ab09399b9185e114dbc">OPTIONAL</span></td></tr><tr><td><mark style="color:orange;">clickAction</mark></td><td>string</td><td>P2P / ADD_MONEY_TO_WALLET / PAYMENT_GATEWAY_CROSS_BTN / LOGIN_FLOW_CROSSBTN / CONTENT / PASS / SUBS / MOBILE / EMAIL / GOOGLE / FACEBOOK / BUY_NOW / RENEW_BTN / CHANGE_PLAN / ADD_ADDRESS / COUPON / POPUP_REDIRECT / POPUP_CLOSE</td><td><span data-option="35e68f1a1c474ab09399b9185e114dbc">OPTIONAL</span></td></tr></tbody></table>

3. **EXIT:** It's an event triggered when the user exits.

<table><thead><tr><th>PARAMETERS</th><th width="123">DATATYPE</th><th width="311">DESCRIPTION</th><th>TYPE<select><option value="684ff3ae388944eb96cce4357fd83b63" label="REDUIRED" color="blue"></option><option value="e8c1ca59890542359555b35cad05ca1d" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="684ff3ae388944eb96cce4357fd83b63">REDUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>EXIT</strong></mark></td><td><span data-option="684ff3ae388944eb96cce4357fd83b63">REDUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="684ff3ae388944eb96cce4357fd83b63">REDUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="684ff3ae388944eb96cce4357fd83b63">REDUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique user ID for each user if he/she is logged in</td><td><span data-option="e8c1ca59890542359555b35cad05ca1d">OPTIONAL</span></td></tr></tbody></table>

4. **PURCHASE:** It's an event triggered when the user makes a purchase.

<table><thead><tr><th width="144">PARAMETERS</th><th width="114">DATATYPE</th><th width="301">DESCRIPTION</th><th>TYPE<select><option value="e4ce0d391eb44dee81e9dcb5dc41b891" label="REQUIRED" color="blue"></option><option value="97397f79400a415da37e264a06e9c8e8" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="e4ce0d391eb44dee81e9dcb5dc41b891">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>PURCHASE</strong></mark></td><td><span data-option="e4ce0d391eb44dee81e9dcb5dc41b891">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="e4ce0d391eb44dee81e9dcb5dc41b891">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="e4ce0d391eb44dee81e9dcb5dc41b891">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique user ID for each user if he/she is logged in</td><td><span data-option="e4ce0d391eb44dee81e9dcb5dc41b891">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">purchaseId</mark></td><td></td><td>A unique ID of the order after making a purchase.</td><td><span data-option="e4ce0d391eb44dee81e9dcb5dc41b891">REQUIRED</span></td></tr><tr><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td></td></tr></tbody></table>

5. **TRANSACTION:** It's an event triggered when the user makes a transaction.

<table><thead><tr><th width="145">PARAMETERS</th><th width="116">DATATYPE</th><th width="304">DESCRIPTION</th><th>TYPE<select><option value="29897c9b10af42d48b88f2f932a1eb25" label="REQUIRED" color="blue"></option><option value="61518fa277c844d296422d3bd5867f9f" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="29897c9b10af42d48b88f2f932a1eb25">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>TRANSACTION</strong></mark></td><td><span data-option="29897c9b10af42d48b88f2f932a1eb25">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="29897c9b10af42d48b88f2f932a1eb25">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="29897c9b10af42d48b88f2f932a1eb25">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique user ID for each user if he/she is logged in</td><td><span data-option="29897c9b10af42d48b88f2f932a1eb25">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">transactionId</mark></td><td></td><td>A unique ID of the order after making a transaction.</td><td><span data-option="29897c9b10af42d48b88f2f932a1eb25">REQUIRED</span></td></tr><tr><td></td><td></td><td></td><td></td></tr></tbody></table>

6. **REGISTRATION:**

<table><thead><tr><th width="147">PARAMETERS</th><th width="119">DATATYPE</th><th width="279">VALIDATION</th><th>TYPE<select><option value="b3243684428d49bb943facc6b1995478" label="REQUIRED" color="blue"></option><option value="255d81018ce9453bbb4819a1ab0a00b7" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="b3243684428d49bb943facc6b1995478">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>REGISTRATION</strong></mark></td><td><span data-option="b3243684428d49bb943facc6b1995478">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="b3243684428d49bb943facc6b1995478">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="b3243684428d49bb943facc6b1995478">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique ID of the order after making a transaction.</td><td><span data-option="b3243684428d49bb943facc6b1995478">REQUIRED</span></td></tr></tbody></table>

6. **VALIDATION:**&#x20;

<table><thead><tr><th width="143">PARAMETERS</th><th width="117">DATATYPE</th><th width="316">DESCRIPTION</th><th>TYPE<select><option value="d44abd8e4edb45f4be42fcd4f17ede9a" label="REQUIRED" color="blue"></option><option value="d055451ef49146aea0175d467306f8db" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>string</td><td>The unique clientId is found on the dashboard.</td><td><span data-option="d44abd8e4edb45f4be42fcd4f17ede9a">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td>string</td><td><mark style="background-color:orange;"><strong>VALIDATION</strong></mark></td><td><span data-option="d44abd8e4edb45f4be42fcd4f17ede9a">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td>string</td><td>PAGE / PAYWALL / CONTENT_FLOW_LOGIN / CONTENT_FLOW_OTP / CONTENT_FLOW_ADD_MONEY_PAGE / CONTENT_FLOW_PAYMENT_GATEWAY / SSO_LOGIN / SSO_OTP / UDB / UDB_LOGIN / UDB_OTP / SUBS_LOGIN / SUBS_OTP / POPUP / SLP / SAP / SRP / SUBS_PAYMENT_GATEWAY / FAV / FAV_ICON / USER_BAR / RECOMMENDATION_POPUP</td><td><span data-option="d44abd8e4edb45f4be42fcd4f17ede9a">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>uuid</td><td>A unique anonymous ID for each user.</td><td><span data-option="d44abd8e4edb45f4be42fcd4f17ede9a">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userId</mark></td><td>string</td><td>A unique ID of the order after making a transaction.</td><td><span data-option="d44abd8e4edb45f4be42fcd4f17ede9a">REQUIRED</span></td></tr></tbody></table>


# SSO Login Flow

<table><thead><tr><th width="174">PARAMETERS</th><th width="324">Description</th><th>DATATYPE</th><th><select><option value="59f54b85d1b44dedb3fc87b01340c1c7" label="REQUIRED" color="blue"></option><option value="5d81d115016a4a67943345e8408d77ba" label="OPTIONAL" color="blue"></option></select></th></tr></thead><tbody><tr><td><mark style="color:orange;">clientId</mark></td><td>The unique clientId is found on the dashboard.</td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventType</mark></td><td></td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">eventLocation</mark></td><td></td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">anonId</mark></td><td>A unique anonymous ID for each user.</td><td>uuid</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">url</mark></td><td></td><td>string</td><td><span data-option="5d81d115016a4a67943345e8408d77ba">OPTIONAL</span></td></tr><tr><td><mark style="color:orange;">isCookieBlocked</mark></td><td></td><td>boolean</td><td><span data-option="5d81d115016a4a67943345e8408d77ba">OPTIONAL</span></td></tr><tr><td><mark style="color:orange;">contentId</mark></td><td>A unique id of each content.</td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">clickAction</mark></td><td></td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">validationType</mark></td><td></td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">firstTimeLogin</mark></td><td></td><td>boolean</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr><tr><td><mark style="color:orange;">userAgent</mark></td><td></td><td>string</td><td><span data-option="59f54b85d1b44dedb3fc87b01340c1c7">REQUIRED</span></td></tr></tbody></table>

<details>

<summary>User SignUp View Event</summary>

**Description**

It is an event that is triggered when the user views the sign-up/ login page for the first time.

**Example:**

```json
{
"eventType": "VIEW",
"eventLocation": "SSO_SIGNUP",
"clientId": "5f92a62013332e0f667794dc",
"anonId": "b79064d2-2256-4c36-ad06-8c38cc0396c7",
"url": "http://localhost:9000/test.html",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"isCookieBlocked": 0,
"contentId":'contentId-1'
}
```

</details>

<details>

<summary>User Login View Event</summary>

**Description**

It is an event that is triggered when the user views the login page.

**Example**

```json
{
"eventType": "VIEW",
"eventLocation": "SSO_LOGIN",
"clientId": "5f92a62013332e0f667794dc",
"anonId": "b79064d2-2256-4c36-ad06-8c38cc0396c7",
"url": "http://localhost:9000/test.html",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"isCookieBlocked": 0,
"contentId": 'article-20',
}
```

</details>

<details>

<summary>User OTP View Event</summary>

**Description**

It is an event that is triggered when the user views the OTP Page.

**Example**

```json
{
"eventType": "VIEW",
"eventLocation": "SSO_LOGIN_OTP",
"clientId": "5f92a62013332e0f667794dc",
"anonId": "b79064d2-2256-4c36-ad06-8c38cc0396c7",
"url": "http://localhost:9000/test.html",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"isCookieBlocked": 0,
"contentId": 'article-20',
}
```

**Note: This event is only needed to be sent when the Login is based on OTP.**

</details>

<details>

<summary>User Click Event</summary>

**Description**

It is an event that is triggered when the user performs the click action when he/she logs in.

**Example**

```json
{
"eventType": "CLICK",
"eventLocation": "SSO_LOGIN",
"clickAction": 'EMAIL' | 'MOBILE' | 'GOOGLE'
"clientId": "5f92a62013332e0f667794dc",
"anonId": "b79064d2-2256-4c36-ad06-8c38cc0396c7",
"url": "http://localhost:9000/test.html",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"isCookieBlocked": 0,
"contentId": 'article-20',
}
```

</details>

<details>

<summary>User Registration Event</summary>

**Description**

It is an event that is triggered when the user registers to your platform for the first time.

**Example**

```json
{
"eventType": "REGISTRATION",
"eventLocation": "SSO_LOGIN",
"clientId": "5f92a62013332e0f667794dc",
"anonId": "b79064d2-2256-4c36-ad06-8c38cc0396c7",
"url": "http://localhost:9000/test.html",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"isCookieBlocked": 0
"userId": "5f92a62013332e0f667794dc",
"validationType": "OTP",
"firstTimeLogin": 1,
"contentId": 'article-20',
}
```

</details>

<details>

<summary>User Validation Event</summary>

**Description**

It is an event that is triggered when the user is validated whenever he logs in.

**Example**

```json
{
"eventType": "VALIDATION",
"eventLocation": "SSO_LOGIN",
"clientId": "5f92a62013332e0f667794dc",
"anonId": "b79064d2-2256-4c36-ad06-8c38cc0396c7",
"url": "http://localhost:9000/test.html",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"isCookieBlocked": 0
"userId": "5f92a62013332e0f667794dc",
"validationType": "OTP",
"firstTimeLogin": 1,
"contentId": 'article-20',
}
```

</details>


# Discount Coupon

The Discount Coupon is designed to facilitate the creation and management of two primary types of coupon templates: Static and Dynamic.

### **Coupon Templates Overview:**

{% tabs %}
{% tab title="Static Coupons" %}

* **Single Code Use:** Static coupons are characterized by a single, unchanging coupon code for every customer.
  {% endtab %}

{% tab title="Dynamic Coupons" %}
**Types:**

1. **AUTO\_ACCEPT:** Allows clients to generate coupons based on a list of codes they provide.
2. **AUTO\_ALLOCATE:** Enables the automatic generation of coupons, with quantities specified by the client.&#x20;
3. **CSV Upload:** This enables the client to upload a CSV file containing coupon codes for storing in the database. The CSV file must have a header named 'codes' for effective coupon code creation and storage in the database.

**Pre-Generation:** Dynamic coupons can also be pre-generated (by prefix, suffix, and count parameters) and stored for future use. Each coupon generated will be 12 characters long.
{% endtab %}
{% endtabs %}

### Coupon Creation Process:

{% tabs %}
{% tab title="Static Coupon" %}

* **Single Coupon Code:** Clients define a unique coupon code, adhering to character limits and no-space rules.&#x20;
* **Usage Limits:** Setting a limit on how many times the static coupon can be redeemed.
  {% endtab %}

{% tab title="Dynamic Coupon" %}

* **Pre-Generation:** Dynamic coupons can also be pre-generated (by prefix, suffix, and count parameters) and stored for future use. Each coupon generated will be 12 characters long.&#x20;
* **AUTO\_ACCEPT Customization:**&#x20;

**Client-Provided Codes:** Clients upload a list of unique coupon codes, which the API uses to generate coupons.

**Coupon Characteristics:** Setting rules such as discount type, duration, and applicable subscriptions.

* &#x20;**AUTO\_ALLOCATE Customization:**&#x20;

**On-the-Fly Generation:** Allows clients to specify the number of coupons to be generated automatically by the API.

**Customization Options:** Setting prefixes, suffixes, and the number of random digits in the coupon codes.&#x20;

* **Pre-Generation and Storage:** Ability to pre-generate and store Dynamic coupons in the database
  {% endtab %}
  {% endtabs %}

**Enhanced Management Features:**

1. **Coupon Listing:** Displaying coupons in a card format with comprehensive statistics.&#x20;
2. **Data Filtering:** Options to filter by coupon type, redemption rate, and date ranges.&#x20;
3. **Coupon Actions:** Facilities to edit, delete, and toggle the active status of coupons.&#x20;
4. **API Ingestion and New Coupon Creation:** Initiating new coupon creation.

> **Note:**  Both Static and Dynamic coupons can be applied on the Subscription Landing Page (SLP) and Subscription Review Page (SRP), with features like auto-apply and removal options


# Dynamic Coupon API Generation:

This API endpoint facilitates the generation of dynamic discount coupons based on specific templates: AUTO\_ALLOCATE and AUTO\_ACCEPT flag set during template generation.

## Basic Auth:

<mark style="color:green;">`POST`</mark> `{API_URL}/subscription/discount-coupon-template/generate-user-coupon`

Enter[ API-KEY and API-Secret](https://sandbox-client.conscent.in/client/dashboard/Documentation) as username and password respectively.

#### Request Body

| Name                                           | Type             | Description                                          |
| ---------------------------------------------- | ---------------- | ---------------------------------------------------- |
| couponName<mark style="color:red;">\*</mark>   | String           | <p>Unique identifier for the coupon name.</p><p></p> |
| clientId<mark style="color:red;">\*</mark>     | String           | Unique identifier for the client.                    |
| quantity<mark style="color:red;">\*</mark>     | Integer          | Number of coupons to be generated.                   |
| couponCodes <mark style="color:red;">\*</mark> | Array of Strings | Predefined coupon codes provided by the client.      |

{% tabs %}
{% tab title="201: Created Details of the generated coupons including identifiers and metadata are provided in the response." %}
Details of the generated coupons including identifiers and metadata are provided in the response.
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Example for AUTO\_ALLOCATE :" %}

```json
{
  "couponName": "Test Dynamic Coupon",
  "clientId": "YOUR_CLIENT_ID",
  "quantity": 10
}
```

{% endtab %}

{% tab title="Example for AUTO\_ACCEPT :" %}

```json
{ "couponName": "Test Dynamic Coupon",
 "clientId": "5f92a62013332e0f667794dc", 
"couponCodes": ["TESTDIWALI500", "fdhfuhiufh", "FUNCHRISTMAS"] }
```

{% endtab %}
{% endtabs %}

<details>

<summary><strong>Rules and Constraints:</strong></summary>

Functionality of AUTO\_ALLOCATE and AUTO\_ACCEPT templates are exclusive:&#x20;

**AUTO\_ALLOCATE:** Automatic generation in specified quantity.&#x20;

**AUTO\_ACCEPT:** Generation based on client-provided **couponCodes.**

The quantity parameter is ignored for **AUTO\_ACCEPT,** and **couponCodes** for **AUTO\_ALLOCATE.**&#x20;

**couponCodes** must be unique and follow format/validation rules of the template.&#x20;

**Quantity Limitation:** The quantity of coupons requested in an AUTO\_ALLOCATE template cannot exceed the maximum quantity set for that template in the dashboard during template creation. Attempts to generate coupons beyond this limit will result in an error

</details>

**Error Handling:** Error messages and codes for scenarios like invalid template IDs, missing fields, or invalid coupon codes. Specific errors will be returned if the requested quantity exceeds the template's maximum limit.


# New Webhooks


# Meter Banner Webhook

A Meter Banner Webhook is used in digital publishing or content monetization platforms to trigger actions related to metered paywalls or content access limits.

**Meter\_Banner.Close:** This event is triggered when the users press the 'X' or 'Close' button on the meter banner.

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "meter_banner.close",
  "contains": [
    "meteringBanner",
    "user"
  ],
  "payload": {
    "meteringBanner": {
      "_id": "65704832df3fbf05635ec357",
      "createdAt": "2023-12-06T10:08:50.649Z",
      "updatedAt": "2023-12-06T10:08:50.911Z",
      "deviceType": "DESKTOP",
      "name": "CustomURL"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186126
}

```

**Meter\_Banner.Click: This event is triggered when the users click on the button in the meter banner.**

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "meter_banner.click",
  "contains": [
    "action",
    "meteringBanner",
    "user"
  ],
  "payload": {
    "action": {
      "clickAction": "SUBS",
      "pageUrl": "https://dashboards.conscent.art/Meter?clientId=65015ff10070846629fb981e&anonId=4a92915b-a0ee-413d-9526-cfdb064caf7b&paywallId=65704832df3fbf05635ec357&userSourceData=DIRECT&clientContentId=Client-Story-Id-2&hide=000&pageUrl=https%253A%252F%252Fcsc-mock.netlify.app%252F65015ff10070846629fb981e%252FClient-Story-Id-2&sessionId=65e01bdad03692125f1f3540&showLogin=true&bannerMeter=2/2",
      "contentId": "Client-Story-Id-2"
    },
    "meteringBanner": {
      "_id": "65704832df3fbf05635ec357",
      "createdAt": "2023-12-06T10:08:50.649Z",
      "updatedAt": "2023-12-06T10:08:50.911Z",
      "deviceType": "DESKTOP",
      "name": "CustomURL"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186212
}

```

**Meter\_Banner.view: This event is triggered when the users view the meter banner.**

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "meter_banner.view",
  "contains": [
    "action",
    "meteringBanner",
    "user"
  ],
  "payload": {
    "action": {
      "pageUrl": "https://dashboards.conscent.art/Meter?clientId=65015ff10070846629fb981e&anonId=4a92915b-a0ee-413d-9526-cfdb064caf7b&paywallId=65704832df3fbf05635ec357&userSourceData=DIRECT&clientContentId=Client-Story-Id-1&hide=000&pageUrl=https%253A%252F%252Fcsc-mock.netlify.app%252F65015ff10070846629fb981e%252FClient-Story-Id-1&sessionId=65e01bdad03692125f1f3540&showLogin=true&bannerMeter=1/1",
      "contentId": "Client-Story-Id-1"
    },
    "meteringBanner": {
      "_id": "65704832df3fbf05635ec357",
      "createdAt": "2023-12-06T10:08:50.649Z",
      "updatedAt": "2023-12-06T10:08:50.911Z",
      "deviceType": "DESKTOP",
      "name": "CustomURL"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186078
}
```


# Paywall Webhook

A Paywall Webhook is a mechanism used in digital publishing platforms or subscription-based services to notify a system or application about events related to paywalls.

**Paywall.exit:** This event is triggered when the users saw the paywall but decided not to continue.

> Please note that this data may not always be precise because this event can be skipped in many special situations.

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "paywall.exit",
  "contains": [
    "paywall",
    "user"
  ],
  "payload": {
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186212
}
```

**Paywall.click:** This event is triggered when the users click on one of the CTAs of the paywall.

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "paywall.click",
  "contains": [
    "action",
    "paywall",
    "user"
  ],
  "payload": {
    "action": {
      "clickAction": "CONTENT",
      "numCta": 3,
      "pageUrl": "https://dashboards.conscent.art/overlay?clientId=65015ff10070846629fb981e&anonId=4a92915b-a0ee-413d-9526-cfdb064caf7b&paywallId=65cb7057e57605058015b407&userSourceData=DIRECT&clientContentId=Client-Story-Id-2&hide=000&pageUrl=https%253A%252F%252Fcsc-mock.netlify.app%252F65015ff10070846629fb981e%252FClient-Story-Id-2&sessionId=65e01bdad03692125f1f3540&showLogin=true",
      "contentId": "Client-Story-Id-2"
    },
    "paywall": {
      "_id": "65cb7057e57605058015b407",
      "state": "SAVED",
      "enable": false,
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "name": "inArticle BY Suyog",
      "createdAt": "2024-02-13T13:36:23.378Z",
      "updatedAt": "2024-02-14T12:52:00.520Z",
      "__v": 0,
      "version": "1"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186668
}

```

**Paywall.view:**  This event is triggered when the users view the paywall.

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "paywall.view",
  "contains": [
    "action",
    "paywall",
    "user"
  ],
  "payload": {
    "action": {
      "numCta": 3,
      "pageUrl": "https://dashboards.conscent.art/overlay?clientId=65015ff10070846629fb981e&anonId=4a92915b-a0ee-413d-9526-cfdb064caf7b&paywallId=65cb7057e57605058015b407&userSourceData=DIRECT&clientContentId=Client-Story-Id-2&hide=000&pageUrl=https%253A%252F%252Fcsc-mock.netlify.app%252F65015ff10070846629fb981e%252FClient-Story-Id-2&sessionId=65e01bdad03692125f1f3540&showLogin=true",
      "contentId": "Client-Story-Id-2"
    },
    "paywall": {
      "_id": "65cb7057e57605058015b407",
      "state": "SAVED",
      "enable": false,
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "name": "inArticle BY Suyog",
      "createdAt": "2024-02-13T13:36:23.378Z",
      "updatedAt": "2024-02-14T12:52:00.520Z",
      "__v": 0,
      "version": "1"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "New Delhi (Okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186393
}
```


# SignUp Webhook

A Signup Webhook is used in online platforms to notify or trigger actions in response to user signups or registrations.

**Signup.success:** This event is triggered when the users manage to sign up for a new account successfully.

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "signup.success",
  "contains": [
    "user"
  ],
  "payload": {
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709186010
}

```

**Signup.failed:** This event is triggered when the users are unable to create a new account.

```json
{
  "entity": "event",
  "user_id": "65e01f76d03692125f1f355e",
  "event": "signup.failed",
  "contains": [
    "user"
  ],
  "payload": {
    "user": {
      "phoneNumber": "8838239889",
      "userId": "65e01f76d03692125f1f355e",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8838239889"
    }
  },
  "client_info": {
    "deviceType": "desktop"
  },
  "created_at": 1709186936
}
```


# Refund Webhook

A Refund Webhook is used in payment processing systems to notify or trigger actions in response to refund transactions.

**Refund.pay\_per\_use:** This event is triggered when a refund is created for a Pay-per-use.

```json
{
  "entity": "event",
  "user_id": "65dde318171dbd055b502de3",
  "event": "refunded.pay_per_use",
  "contains": [
    "refund",
    "user"
  ],
  "payload": {
    "refund": {
      "_id": "65e0220ed03692125f1f3592",
      "paymentGatewayRefundId": "rfnd_NgatMWS157Nzyu",
      "amount": 1,
      "currency": "INR",
      "cancelAccess": false,
      "userId": "65dde318171dbd055b502de3",
      "clientId": "65015ff10070846629fb981e",
      "createdAt": "2024-02-29T06:19:58.420Z",
      "transactionId": "65dde31b171dbd055b502de8",
      "updatedAt": "2024-02-29T06:20:28.907Z"
    },
    "user": {
      "phoneNumber": "8948948898",
      "userId": "65dde318171dbd055b502de3",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8948948898"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709187629
}

```

**Refund.subscription:** This event is triggered when a refund is created for a subscription.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "refunded.subscription",
  "contains": [
    "user",
    "refund"
  ],
  "payload": {
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833"
    },
    "refund": {
      "_id": "65e01fe8d03692125f1f356a",
      "paymentGatewayRefundId": "rfnd_NgajgFeD4I04Ve",
      "amount": 1,
      "currency": "INR",
      "cancelAccess": false,
      "userId": "65e01719d03692125f1f323f",
      "clientId": "65015ff10070846629fb981e",
      "createdAt": "2024-02-29T06:10:48.435Z",
      "transactionId": "65e01798d03692125f1f33e5",
      "updatedAt": "2024-02-29T06:11:18.961Z"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709187079
}

```

**Refund.pass:** This event is triggered when a refund is created for a pass.

```json
{
  "entity": "event",
  "user_id": "65d44453cc6cfa43c284a19c",
  "event": "refunded.pass",
  "contains": [
    "refund",
    "user"
  ],
  "payload": {
    "refund": {
      "_id": "65e02242d03692125f1f3593",
      "paymentGatewayRefundId": "rfnd_NgauHW7CMRO717",
      "amount": 1,
      "currency": "INR",
      "cancelAccess": false,
      "userId": "65d44453cc6cfa43c284a19c",
      "clientId": "65015ff10070846629fb981e",
      "createdAt": "2024-02-29T06:20:50.593Z",
      "transactionId": "65d44503cc6cfa43c284a1e6",
      "updatedAt": "2024-02-29T06:21:21.144Z"
    },
    "user": {
      "phoneNumber": "9598598585",
      "userId": "65d44453cc6cfa43c284a19c",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (pocket c)",
      "location": {
        "latitude": 28.5246,
        "longitude": 77.2793,
        "postcode": "110001"
      },
      "username": "9598598585"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709187681
}
```


# Purchase Webhook

A Purchase Webhook is used in payment processing systems to notify or trigger actions in response to purchase transactions.

**Purchase.pass:** This event is triggered when a purchase is created after a successful transaction of a Pass

```json
{
  "entity": "event",
  "user_id": "67a33080b06ceb81ad1a0962",
  "event": "purchase.subscription",
  "contains": [
    "purchase",
    "user"
  ],
  "payload": {
    "purchase": {
      "_id": "67a33168b06ceb81ad1a0dbf",
      "location": {
        "latitude": 28.4112,
        "longitude": 77.3132
      },
      "gstComponents": {
        "physical": 0,
        "digital": 0
      },
      "inrGstComponents": {
        "physical": 0,
        "digital": 0
      },
      "cancelAccess": false,
      "contentType": {
        "digital": true,
        "adFree": false,
        "_id": "67a33168b06ceb81ad1a0dbe"
      },
      "migrated": false,
      "partialAccess": false,
      "sectionsInclude": [],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [],
      "tagsExclude": [],
      "userAccount": "67a33080b06ceb81ad1a0962",
      "clientId": "661907c2487ae1aba956dcc4",
      "clientReferenceId": "undefined",
      "buyingPrice": 108,
      "price": 120,
      "country": "IN",
      "city": "faridabad",
      "priceDetails": {
        "price": 120,
        "currency": "INR"
      },
      "type": "SUBSCRIPTION",
      "subscriptionType": {
        "physical": false,
        "digital": true,
        "adFree": false,
        "epaper": false
      },
      "subscriptionTitle": "kuchbhi",
      "subscriptionDetails": {
        "inrPrice": 120,
        "duration": 1
      },
      "transactionId": "67a33168b06ceb81ad1a0dbd",
      "expiryDate": "2025-03-05T09:37:44.468Z",
      "createdAt": "2025-02-05T09:37:44.508Z",
      "updatedAt": "2025-02-05T09:37:44.508Z"
    },
    "user": {
      "email": "asgcdv@gyhh.com",
      "freeTrial": 0,
      "userId": "67a3307bb06ceb81ad1a0945",
      "externalUserId": "67a3307bb06ceb81ad1a0945",
      "address": {
        "apartment": "",
        "landmark": "",
        "city": "",
        "name": "asdf",
        "area": "asdf",
        "pincode": "1234",
        "state": "adsf",
        "country": "AX"
      },
      "name": "ayush",
      "billingAddress": [
        {
          "name": "asdf",
          "apartment": "",
          "area": "asdf",
          "pincode": "1234",
          "landmark": "",
          "city": "",
          "state": "adsf",
          "country": "AX",
          "_id": "67a3313db06ceb81ad1a0b35"
        }
      ],
      "shippingAddress": [
        {
          "name": "adsf",
          "apartment": "",
          "area": "sadf",
          "pincode": "5346576",
          "landmark": "",
          "city": "",
          "state": "asdd",
          "country": "HT",
          "_id": "67a3313db06ceb81ad1a0b36"
        }
      ],
      "dateOfBirth": null,
      "location": {},
      "clientTierId": "673c315bb2deb6e310fbd8f3"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1738748267
}
```

**Purchase.subscription:** This event is triggered when a purchase is created after a successful transaction of a  Subscription.

```json
{
  "entity": "event",
  "user_id": "6745980ff34e079c0a53f4ae",
  "event": "purchase.subscription",
  "contains": [
    "user",
    "purchase"
  ],
  "payload": {
    "user": {
      "email": "k21@k.com",
      "freeTrial": 0,
      "userId": "6745980ff34e079c0a53f4ae",
      "externalUserId": "61259",
      "address": {
        "name": "",
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "location": {},
      "clientTierId": "6719de840ff43042667339a7"
    },
    "purchase": {
      "_id": "674598340ce37e76f7fc3f66",
      "location": {
        "latitude": 28.6031,
        "longitude": 77.1399
      },
      "gstComponents": {
        "physical": 0,
        "digital": 0
      },
      "inrGstComponents": {
        "physical": 0,
        "digital": 0
      },
      "cancelAccess": false,
      "contentType": {
        "digital": true,
        "adFree": false,
        "_id": "674598340ce37e76f7fc3f65"
      },
      "migrated": false,
      "partialAccess": false,
      "sectionsInclude": [],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [],
      "tagsExclude": [],
      "userAccount": "6745980ff34e079c0a53f4ae",
      "clientId": "641b0e856e306e46f88e29c6",
      "buyingPrice": 3780,
      "price": 3780,
      "country": "IN",
      "city": "shahdara",
      "priceDetails": {
        "price": 2520,
        "currency": "INR"
      },
      "type": "SUBSCRIPTION",
      "subscriptionType": {
        "physical": false,
        "digital": false,
        "adFree": false,
        "epaper": true
      },
      "subscriptionTitle": "E-Magazine Access",
      "subscriptionDetails": {
        "inrPrice": 3780,
        "duration": 12
      },
      "transactionId": "67459825b1c5a68745431e13",
      "expiryDate": "2025-11-26T09:43:01.800Z",
      "createdAt": "2024-11-26T09:43:16.937Z",
      "updatedAt": "2024-11-26T09:43:16.984Z"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1732614198
}
```

**Purchase.pay\_per\_use:** This event is triggered when a purchase is created after a successful transaction of a Pay-per-use.

```json
{
  "entity": "event",
  "user_id": "65e01f76d03692125f1f355e",
  "event": "purchase.pay_per_use",
  "contains": [
    "purchase",
    "user"
  ],
  "payload": {
    "purchase": {
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "gstComponents": {
        "physical": 0,
        "digital": 0
      },
      "inrGstComponents": {
        "physical": 0,
        "digital": 0
      },
      "_id": "65e0235ed03692125f1f35c2",
      "cancelAccess": false,
      "contentType": {
        "digital": true,
        "adFree": false,
        "_id": "65e0235e36cfe5f49666f7b2"
      },
      "categories": [],
      "bundle": false,
      "bundleContentIds": [],
      "paymentType": [
        "NEW"
      ],
      "migrated": false,
      "partialAccess": false,
      "sectionsInclude": [],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [],
      "tagsExclude": [],
      "proRataAppliedPurchases": [],
      "userAccount": "65e01f76d03692125f1f355e",
      "clientId": "65015ff10070846629fb981e",
      "paywallId": "65cb7057e57605058015b407",
      "clientContentId": "Client-Story-Id-2",
      "contentId": "65115336f1a61f0a58d4ae4e",
      "buyingPrice": 8,
      "price": 10,
      "country": "IN",
      "city": "new delhi (okhla phase i)",
      "userCountry": "IN",
      "expiryDate": "2024-03-07T06:25:24.493Z",
      "priceDetails": {
        "price": 10,
        "currency": "INR",
        "_id": "65e0235e36cfe5f49666f7b3"
      },
      "type": "CONTENT",
      "operatingSystem": "Mac OS",
      "device": "desktop",
      "transactionId": "65e02354d03692125f1f35c0",
      "bundleSubscriptions": [],
      "createdAt": "2024-02-29T06:25:34.333Z",
      "updatedAt": "2024-02-29T06:25:34.333Z",
      "__v": 0
    },
    "user": {
      "phoneNumber": "8838239889",
      "userId": "65e01f76d03692125f1f355e",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8838239889"
    }
  },
  "client_info": {
    "deviceType": "desktop"
  },
  "created_at": 1709187934
}

```

**Purchase.bundle:**

```json
{
  "entity": "event",
  "user_id": "65e59ddb6efe72055d89ec87",
  "event": "purchase.bundle",
  "contains": [
    "purchase",
    "user"
  ],
  "payload": {
    "purchase": {
      "location": {
        "latitude": 28.5246,
        "longitude": 77.2793,
        "postcode": "110001"
      },
      "gstComponents": {
        "physical": 0,
        "digital": 899
      },
      "inrGstComponents": {
        "physical": 0,
        "digital": 899
      },
      "_id": "65e5a2576efe72055d89ed11",
      "cancelAccess": false,
      "contentType": {
        "digital": true,
        "adFree": false,
        "_id": "65e5a26036cfe5f496673315"
      },
      "categories": [],
      "bundle": true,
      "bundleContentIds": [],
      "paymentType": [
        "NEW"
      ],
      "migrated": false,
      "partialAccess": false,
      "sectionsInclude": [],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [],
      "tagsExclude": [],
      "proRataAppliedPurchases": [],
      "userAccount": "65e59ddb6efe72055d89ec87",
      "clientId": "65015ff10070846629fb981e",
      "buyingPrice": 854.05,
      "price": 899,
      "clientName": "Black Panther",
      "country": "IN",
      "city": "new delhi (pocket c)",
      "userCountry": "IN",
      "priceDetails": {
        "price": 899,
        "currency": "INR",
        "_id": "65e5a26036cfe5f496673316"
      },
      "type": "SUBSCRIPTION",
      "subscriptionType": {
        "physical": false,
        "digital": true,
        "adFree": false,
        "_id": "65e5a26036cfe5f496673317"
      },
      "subscriptionTitle": "Bundled Subscription",
      "utmParameters": {
        "utm_source": "KJK"
      },
      "operatingSystem": "Mac OS",
      "device": "desktop",
      "bundleSubscriptions": [
        {
          "_id": "650166680070846629fb9866",
          "clientId": "601a8ea4f2149f089782814f",
          "tierId": "650166680070846629fb9868"
        }
      ],
      "subscriptionDetails": {
        "inrPrice": 899,
        "duration": 0,
        "_id": "65e5a26036cfe5f496673318"
      },
      "transactionId": "65e5a2576efe72055d89ed13",
      "expiryDate": "2024-03-04T10:28:47.967Z",
      "createdAt": "2024-03-04T10:28:47.967Z",
      "updatedAt": "2024-03-04T10:28:47.967Z",
      "__v": 0
    },
    "user": {
      "phoneNumber": "9821828889",
      "userId": "65e59ddb6efe72055d89ec87",
      "country": "IN",
      "address": {
        "apartment": "1212",
        "pincode": "12",
        "city": "1212",
        "country": "India",
        "state": "1212",
        "area": "",
        "landmark": ""
      },
      "name": "ajdkllasd",
      "dateOfBirth": "0222-03-12T00:00:00.000Z",
      "city": "new delhi (pocket c)",
      "location": {
        "latitude": 28.5246,
        "longitude": 77.2793,
        "postcode": "110001"
      },
      "username": "9821828889"
    }
  },
  "client_info": {
    "deviceType": "desktop"
  },
  "created_at": 1709548128
}
```


# Subscription Landing Page Webhook

A Subscription Landing Page Webhook is used in subscription management systems or marketing automation platforms to trigger actions related to user interactions with subscription landing page.

**Sub\_landing\_page.click:** This event is triggered when users click on the landing page.

```json
{
  "entity": "event",
  "user_id": "65e800a2823acd057d66f897",
  "event": "sub_landing_page.click",
  "contains": [
    "landingPage",
    "tier",
    "subscription",
    "user"
  ],
  "payload": {
    "landingPage": {
      "_id": "652e3c6ce7354805632dc7ce",
      "title": "gcp dashboard tsb",
      "description": "pahle istemal kare fir vishwas kare all copyright save @itachi_uchiha",
      "headerRedirectUrl": "https://conscent-demo-new.netlify.app/",
      "desktopBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - desktopBanner-4c5e36.png",
      "mobileBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - mobileBanner-096872.png",
      "brandLogo": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - brandLogo-4cee52.png",
      "template": "t1",
      "subscriptions": [
        {
          "_id": "65c4e2f1f296fa057f3efa9a",
          "priority": 1,
          "recommended": false
        },
        {
          "_id": "65c4e31cf296fa057f3efaa0",
          "priority": 2,
          "recommended": false
        },
        {
          "_id": "65c4e35af296fa057f3efaa6",
          "priority": 3,
          "recommended": false
        },
        {
          "_id": "65c4e377f296fa057f3efaa9",
          "priority": 4,
          "recommended": false
        },
        {
          "_id": "65ca3396cf79e205809d3015",
          "priority": 5,
          "recommended": false
        }
      ],
      "createdAt": "2023-10-17T07:49:01.515Z",
      "updatedAt": "2024-03-05T12:48:48.329Z"
    },
    "tier": {
      "_id": "65c4e31cf296fa057f3efaa2",
      "currency": "INR",
      "basePrice": 0,
      "price": 100,
      "durationMonths": 1,
      "priceOverrides": {
        "country": []
      },
      "gstComponents": {},
      "rzpPlainId": "plan_JDJjFwwOG1V8a3"
    },
    "subscription": {
      "_id": "65c4e31cf296fa057f3efaa0",
      "benefits": "test2",
      "physical": false,
      "digital": true,
      "title": "football",
      "clientId": "65015ff10070846629fb981e",
      "tiers": [
        {
          "_id": "65c4e31cf296fa057f3efaa2",
          "currency": "INR",
          "basePrice": 0,
          "price": 100,
          "durationMonths": 1,
          "priceOverrides": {
            "country": []
          },
          "gstComponents": {},
          "rzpPlainId": "plan_JDJjFwwOG1V8a3"
        }
      ],
      "iconUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/subscriptions/65c4e31cf296fa057f3efaa0-e5134a.png",
      "createdAt": "2024-02-08T14:20:12.687Z",
      "updatedAt": "2024-02-20T13:21:27.717Z",
      "partialAccess": true,
      "sectionsInclude": [
        "goal",
        "foot"
      ],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [
        "football"
      ],
      "tagsExclude": []
    },
    "user": {
      "phoneNumber": "8382938898",
      "userId": "65e800a2823acd057d66f897",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (pocket c)",
      "location": {
        "latitude": 28.5246,
        "longitude": 77.2793,
        "postcode": "110001"
      },
      "username": "8382938898",
      "clientTierId": "65c4e31cf296fa057f3efaa2"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709703417
}
```

**Sub\_landing\_page.view:** This event is triggered when users view the landing page.

```json
{
  "entity": "event",
  "user_id": "65e5b0a68a113905625dffd2",
  "event": "sub_landing_page.view",
  "contains": [
    "landingPage",
    "user"
  ],
  "payload": {
    "landingPage": {
      "_id": "652e3c6ce7354805632dc7ce",
      "title": "gcp dashboard tsb",
      "description": "pahle istemal kare fir vishwas kare all copyright save @itachi_uchiha",
      "headerRedirectUrl": "https://conscent-demo-new.netlify.app/",
      "desktopBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - desktopBanner-4c5e36.png",
      "mobileBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - mobileBanner-096872.png",
      "brandLogo": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - brandLogo-4cee52.png",
      "template": "t1",
      "subscriptions": [
        {
          "_id": "65c4e2f1f296fa057f3efa9a",
          "priority": 1,
          "recommended": false
        },
        {
          "_id": "65c4e31cf296fa057f3efaa0",
          "priority": 2,
          "recommended": false
        },
        {
          "_id": "65c4e35af296fa057f3efaa6",
          "priority": 3,
          "recommended": false
        },
        {
          "_id": "65c4e377f296fa057f3efaa9",
          "priority": 4,
          "recommended": false
        },
        {
          "_id": "65c4e3bff296fa057f3efaaf",
          "priority": 5,
          "recommended": false
        },
        {
          "_id": "65ca3396cf79e205809d3015",
          "priority": 6,
          "recommended": false
        },
        {
          "_id": "65dc604d5f5b1d0559c03b10",
          "priority": 7,
          "recommended": false
        }
      ],
      "createdAt": "2023-10-17T07:49:01.515Z",
      "updatedAt": "2024-02-26T09:57:27.661Z"
    },
    "user": {
      "phoneNumber": "8493849889",
      "userId": "65e5b0a68a113905625dffd2",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (pocket c)",
      "location": {
        "latitude": 28.5246,
        "longitude": 77.2793,
        "postcode": "110001"
      },
      "username": "8493849889"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709552005
}
```

**Sub\_landing\_page.exit:** This event is triggered when users open the landing page but decide not to continue.

> Please note that this data may not always be precise because this event can be skipped in many special situations.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "subscription_landing.exit",
  "contains": [
    "landingPage",
    "user"
  ],
  "payload": {
    "landingPage": {
      "_id": "652e3c6ce7354805632dc7ce",
      "title": "gcp dashboard tsb",
      "description": "pahle istemal kare fir vishwas kare all copyright save @itachi_uchiha",
      "headerRedirectUrl": "https://conscent-demo-new.netlify.app/",
      "desktopBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - desktopBanner-4c5e36.png",
      "mobileBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - mobileBanner-096872.png",
      "brandLogo": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - brandLogo-4cee52.png",
      "template": "t1",
      "subscriptions": [
        {
          "_id": "65c4e2f1f296fa057f3efa9a",
          "priority": 1,
          "recommended": false
        },
        {
          "_id": "65c4e31cf296fa057f3efaa0",
          "priority": 2,
          "recommended": false
        },
        {
          "_id": "65c4e35af296fa057f3efaa6",
          "priority": 3,
          "recommended": false
        },
        {
          "_id": "65c4e377f296fa057f3efaa9",
          "priority": 4,
          "recommended": false
        },
        {
          "_id": "65c4e3bff296fa057f3efaaf",
          "priority": 5,
          "recommended": false
        },
        {
          "_id": "65ca3396cf79e205809d3015",
          "priority": 6,
          "recommended": false
        },
        {
          "_id": "65dc604d5f5b1d0559c03b10",
          "priority": 7,
          "recommended": false
        }
      ],
      "createdAt": "2023-10-17T07:49:01.515Z",
      "updatedAt": "2024-02-26T09:57:27.661Z"
    },
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709184873
}
```


# Popup Webhook

A Popup Webhook is used  to trigger actions or notifications based on user interactions with pop-up elements on a website or web application.

**Popup.click:** This event is triggered when users click on the popup.

```json
{
  "entity": "event",
  "user_id": "65e026f7d03692125f1f36fa",
  "event": "popup.click",
  "contains": [
    "action",
    "user",
    "popup"
  ],
  "payload": {
    "action": {
      "clickAction": "POPUP_REDIRECT",
      "pageUrl": "https://csc-mock.netlify.app/65015ff10070846629fb981e/Client-Story-Id-7"
    },
    "user": {
      "phoneNumber": "8943489898",
      "userId": "65e026f7d03692125f1f36fa",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8943489898"
    },
    "popup": {
      "_id": "65a66ec068557b0579a275b5",
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "title": "Pop Ferrari",
      "link": "https://conscent.ai/",
      "version": "v2",
      "type": "DESKTOP",
      "imageFileName": "CaaRRar.jpg",
      "imageFileSizeBytes": 291427,
      "imageUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/popups/65a66ec068557b0579a275b5-desktop-f84b9e",
      "createdAt": "2024-01-16T11:55:45.001Z",
      "updatedAt": "2024-01-16T11:55:45.001Z",
      "__v": 0
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709188867
}

```

**Popup.close:** This event is triggered when users click the 'X' or 'Close' button on the Pop-Up.

```json
{
  "entity": "event",
  "user_id": "65e026f7d03692125f1f36fa",
  "event": "popup.close",
  "contains": [
    "action",
    "popup",
    "user"
  ],
  "payload": {
    "action": {
      "clickAction": "POPUP_CLOSE",
      "pageUrl": "https://csc-mock.netlify.app/65015ff10070846629fb981e/Client-Story-Id-7"
    },
    "popup": {
      "_id": "65a66ec068557b0579a275b5",
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "title": "Pop Ferrari",
      "link": "https://conscent.ai/",
      "version": "v2",
      "type": "DESKTOP",
      "imageFileName": "CaaRRar.jpg",
      "imageFileSizeBytes": 291427,
      "imageUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/popups/65a66ec068557b0579a275b5-desktop-f84b9e",
      "createdAt": "2024-01-16T11:55:45.001Z",
      "updatedAt": "2024-01-16T11:55:45.001Z",
      "__v": 0
    },
    "user": {
      "phoneNumber": "8943489898",
      "userId": "65e026f7d03692125f1f36fa",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8943489898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709188871
}

```

**Popup.view:** This event is triggered when users view the popup.

```json
{
  "entity": "event",
  "user_id": "65e026f7d03692125f1f36fa",
  "event": "popup.view",
  "contains": [
    "action",
    "popup",
    "user"
  ],
  "payload": {
    "action": {
      "pageUrl": "https://csc-mock.netlify.app/65015ff10070846629fb981e/Client-Story-Id-7"
    },
    "popup": {
      "_id": "65a66ec068557b0579a275b5",
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "title": "Pop Ferrari",
      "link": "https://conscent.ai/",
      "version": "v2",
      "type": "DESKTOP",
      "imageFileName": "CaaRRar.jpg",
      "imageFileSizeBytes": 291427,
      "imageUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/popups/65a66ec068557b0579a275b5-desktop-f84b9e",
      "createdAt": "2024-01-16T11:55:45.001Z",
      "updatedAt": "2024-01-16T11:55:45.001Z",
      "__v": 0
    },
    "user": {
      "phoneNumber": "8943489898",
      "userId": "65e026f7d03692125f1f36fa",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8943489898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709188865
}

```


# User Update Webhook

This user update webhook is triggered when users information such as phone number email, address, or name has been changed.

```json
{
  "entity": "event",
  "user_id": "65e00ed4d821380560e3c919",
  "event": "user.update",
  "contains": [
    "user"
  ],
  "payload": {
    "user": {
      "phoneNumber": "8384387383",
      "email": "rfsd@wrsgdf.fsgv",
      "userId": "65e00ed4d821380560e3c919",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "erfsgd vcdfs",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8384387383"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709182698
}

```


# Payment Gateway Webhook

A Payment Gateway Webhook is a mechanism used by payment gateways to notify merchants or service providers about events or changes related to payment transactions in real-time.

**Payment\_Gateway.view:** This event is triggered when users view the payment gateway pop-up.

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "payment_gateway.view",
  "contains": [
    "action",
    "user"
  ],
  "payload": {
    "action": {
      "pageUrl": "https://dashboards.conscent.art/overlay?clientId=65015ff10070846629fb981e&anonId=4a92915b-a0ee-413d-9526-cfdb064caf7b&paywallId=65cb7057e57605058015b407&userSourceData=DIRECT&clientContentId=Client-Story-Id-2&hide=000&pageUrl=https%253A%252F%252Fcsc-mock.netlify.app%252F65015ff10070846629fb981e%252FClient-Story-Id-2&sessionId=65e01bdad03692125f1f3540&showLogin=true",
      "contentId": "Client-Story-Id-2"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709186668
}

```

**Payment\_Gateway.close:**

```json
{
  "entity": "event",
  "user_id": "65e01bd8d03692125f1f353d",
  "event": "payment_gateway.close",
  "contains": [
    "action",
    "user"
  ],
  "payload": {
    "action": {
      "clickAction": "PAYMENT_GATEWAY_CROSS_BTN",
      "pageUrl": "https://dashboards.conscent.art/overlay?clientId=65015ff10070846629fb981e&anonId=4a92915b-a0ee-413d-9526-cfdb064caf7b&paywallId=65cb7057e57605058015b407&userSourceData=DIRECT&clientContentId=Client-Story-Id-2&hide=000&pageUrl=https%253A%252F%252Fcsc-mock.netlify.app%252F65015ff10070846629fb981e%252FClient-Story-Id-2&sessionId=65e01bdad03692125f1f3540&showLogin=true",
      "contentId": "Client-Story-Id-2"
    },
    "user": {
      "phoneNumber": "9892898898",
      "userId": "65e01bd8d03692125f1f353d",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "9892898898"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709186818
}
```


# Review Page Webhook

Review Page Webhooks enable merchants to stay informed about customer feedback in real time, allowing them to engage with customers, address concerns, and leverage positive reviews.

**Subscription\_Review\.view:** This event is triggered when a user views the Review Page.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "subscription_review.view",
  "contains": [
    "paywall",
    "user",
    "subscription",
    "tier"
  ],
  "payload": {
    "paywall": {
      "_id": "65cb7057e57605058015b407",
      "state": "SAVED",
      "enable": false,
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "name": "inArticle BY Suyog",
      "createdAt": "2024-02-13T13:36:23.378Z",
      "updatedAt": "2024-02-14T12:52:00.520Z",
      "__v": 0,
      "version": "1"
    },
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833",
      "clientTierId": "65c4e3bff296fa057f3efab1"
    },
    "subscription": {
      "_id": "65c4e3bff296fa057f3efaaf",
      "benefits": "test 5",
      "physical": false,
      "digital": true,
      "title": "super set",
      "clientId": "65015ff10070846629fb981e",
      "tiers": [
        {
          "_id": "65c4e3bff296fa057f3efab1",
          "currency": "INR",
          "basePrice": 0,
          "price": 2,
          "durationMonths": 1,
          "priceOverrides": {
            "country": []
          },
          "gstComponents": {},
          "rzpPlainId": "plan_ItS7yznFF6wFdi"
        }
      ],
      "iconUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/subscriptions/65c4e3bff296fa057f3efaaf-2ff8cd.png",
      "createdAt": "2024-02-08T14:22:55.663Z",
      "updatedAt": "2024-02-27T12:53:17.207Z",
      "partialAccess": true,
      "sectionsInclude": [
        "pawn",
        "goal",
        "batting",
        "goalkeeper"
      ],
      "authorsInclude": [
        "virat",
        "messi",
        "chand"
      ],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [
        "cricket",
        "football",
        "chess",
        "hockey"
      ],
      "tagsExclude": []
    },
    "tier": {
      "_id": "65c4e3bff296fa057f3efab1",
      "currency": "INR",
      "basePrice": 0,
      "price": 2,
      "durationMonths": 1,
      "priceOverrides": {
        "country": []
      },
      "gstComponents": {},
      "rzpPlainId": "plan_ItS7yznFF6wFdi"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709184874
}

```

**Subscription\_Review\.click:** This event is triggered when a user clicks the 'Confirm & Pay' button on the review page.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "subscription_review.click",
  "contains": [
    "action",
    "paywall",
    "user",
    "subscription",
    "tier"
  ],
  "payload": {
    "action": {
      "clickAction": "P2P",
      "pageUrl": "https://dashboards.conscent.art/subscription?clientId=65015ff10070846629fb981e&clientContentId=Client-Story-Id-2&anonId=8822fea9-0bd3-44f5-a8b1-cdcd7c17f35f&landingPageId=652e3c6ce7354805632dc7ce&landingPageTitle=gcp%20dashboard%20tsb&tierId=65c4e3bff296fa057f3efab1&siteUrl=https%3A%2F%2Fcsc-subs-stage.netlify.app%2FConscent%3FclientId%3D65015ff10070846629fb981e%26anonId%3D8822fea9-0bd3-44f5-a8b1-cdcd7c17f35f%26paywallId%3D65cb7057e57605058015b407%26paywallType%3DREGULAR%26clientContentId%3DClient-Story-Id-2%26viewId%3D65e0175ed03692125f1f32b0%26userId%3D65e01719d03692125f1f323f%26referrarData%3DeyJ1c2VyU291cmNlRGF0YSI6IlBBWVdBTEwiLCJyZWZlcnJlciI6IiIsInJlZmVycmVyVXJsIjoiaHR0cHM6Ly9kYXNoYm9hcmRzLmNvbnNjZW50LmFydC8ifQ%3D%3D&viewId=65e0175ed03692125f1f32b0&subscriptionsDataLength=7",
      "contentId": "Client-Story-Id-2"
    },
    "paywall": {
      "_id": "65cb7057e57605058015b407",
      "state": "SAVED",
      "enable": false,
      "deletedAt": null,
      "clientId": "65015ff10070846629fb981e",
      "name": "inArticle BY Suyog",
      "createdAt": "2024-02-13T13:36:23.378Z",
      "updatedAt": "2024-02-14T12:52:00.520Z",
      "__v": 0,
      "version": "1"
    },
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833",
      "clientTierId": "65c4e3bff296fa057f3efab1"
    },
    "subscription": {
      "_id": "65c4e3bff296fa057f3efaaf",
      "benefits": "test 5",
      "physical": false,
      "digital": true,
      "title": "super set",
      "clientId": "65015ff10070846629fb981e",
      "tiers": [
        {
          "_id": "65c4e3bff296fa057f3efab1",
          "currency": "INR",
          "basePrice": 0,
          "price": 2,
          "durationMonths": 1,
          "priceOverrides": {
            "country": []
          },
          "gstComponents": {},
          "rzpPlainId": "plan_ItS7yznFF6wFdi"
        }
      ],
      "iconUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/subscriptions/65c4e3bff296fa057f3efaaf-2ff8cd.png",
      "createdAt": "2024-02-08T14:22:55.663Z",
      "updatedAt": "2024-02-27T12:53:17.207Z",
      "partialAccess": true,
      "sectionsInclude": [
        "pawn",
        "goal",
        "batting",
        "goalkeeper"
      ],
      "authorsInclude": [
        "virat",
        "messi",
        "chand"
      ],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [
        "cricket",
        "football",
        "chess",
        "hockey"
      ],
      "tagsExclude": []
    },
    "tier": {
      "_id": "65c4e3bff296fa057f3efab1",
      "currency": "INR",
      "basePrice": 0,
      "price": 2,
      "durationMonths": 1,
      "priceOverrides": {
        "country": []
      },
      "gstComponents": {},
      "rzpPlainId": "plan_ItS7yznFF6wFdi"
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709184876
}

```

**Subscription\_Review\.exit:** This event is triggered when a user leaves the Review Page without going ahead to make a payment.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "subscription_review.exit",
  "contains": [
    "landingPage",
    "user",
    "tier",
    "subscription"
  ],
  "payload": {
    "landingPage": {
      "_id": "652e3c6ce7354805632dc7ce",
      "title": "gcp dashboard tsb",
      "description": "pahle istemal kare fir vishwas kare all copyright save @itachi_uchiha",
      "headerRedirectUrl": "https://conscent-demo-new.netlify.app/",
      "desktopBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - desktopBanner-4c5e36.png",
      "mobileBannerUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - mobileBanner-096872.png",
      "brandLogo": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/banners/Black Panther - brandLogo-4cee52.png",
      "template": "t1",
      "subscriptions": [
        {
          "_id": "65c4e2f1f296fa057f3efa9a",
          "priority": 1,
          "recommended": false
        },
        {
          "_id": "65c4e31cf296fa057f3efaa0",
          "priority": 2,
          "recommended": false
        }
      ],
      "createdAt": "2023-10-17T07:49:01.515Z",
      "updatedAt": "2024-02-26T09:57:27.661Z"
    },
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833",
      "clientTierId": "65c4e3bff296fa057f3efab1"
    },
    "tier": {
      "_id": "65c4e3bff296fa057f3efab1",
      "currency": "INR",
      "basePrice": 0,
      "price": 2,
      "durationMonths": 1,
      "priceOverrides": {
        "country": []
      },
      "gstComponents": {},
      "rzpPlainId": "plan_ItS7yznFF6wFdi"
    },
    "subscription": {
      "_id": "65c4e3bff296fa057f3efaaf",
      "benefits": "test 5",
      "physical": false,
      "digital": true,
      "title": "super set",
      "clientId": "65015ff10070846629fb981e",
      "tiers": [
        {
          "_id": "65c4e3bff296fa057f3efab1",
          "currency": "INR",
          "basePrice": 0,
          "price": 2,
          "durationMonths": 1,
          "priceOverrides": {
            "country": []
          },
          "gstComponents": {},
          "rzpPlainId": "plan_ItS7yznFF6wFdi"
        }
      ],
      "iconUrl": "https://bkt-conscent-public-stage.storage.googleapis.com/Black Panther/subscriptions/65c4e3bff296fa057f3efaaf-2ff8cd.png",
      "createdAt": "2024-02-08T14:22:55.663Z",
      "updatedAt": "2024-02-27T12:53:17.207Z",
      "partialAccess": true,
      "sectionsInclude": [
        "pawn",
        "goal",
        "batting",
        "goalkeeper"
      ],
      "authorsInclude": [
        "virat",
        "messi",
        "chand"
      ],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [
        "cricket",
        "football",
        "chess",
        "hockey"
      ],
      "tagsExclude": []
    }
  },
  "client_info": {
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop",
    "deviceModel": "Macintosh"
  },
  "created_at": 1709184881
}

```


# Transaction Webhook

The transaction webhook is used  to enable real-time notifications or callbacks regarding transaction-related activities.

**Transaction.complete:** This event is triggered when a transaction is completed from the payment gateway's side.

```json
{
  "entity": "event",
  "user_id": "67a33080b06ceb81ad1a0962",
  "event": "transaction.complete",
  "contains": [
    "transaction",
    "user"
  ],
  "payload": {
    "transaction": {
      "_id": "67a33168b06ceb81ad1a0dbd",
      "status": "COMPLETE",
      "refundStatus": "NOT_INITIATED",
      "orderId": "order_PrywmVklvlzMsW",
      "clientReferenceId": "undefined",
      "amount": 120,
      "currency": "INR",
      "paymentGateway": "RAZORPAY",
      "paymentId": "pay_PryxM9rhzn90Wz",
      "paymentMode": "CARD",
      "createdAt": "2025-02-05T09:37:44.490Z",
      "updatedAt": "2025-02-05T09:37:44.532Z",
      "gatewaySubscriptionId": "sub_PrywkXYU04LWwI",
      "subscriptionDetail": []
    },
    "user": {
      "email": "asgcdv@gyhh.com",
      "userId": "67a3307bb06ceb81ad1a0945",
      "externalUserId": "67a3307bb06ceb81ad1a0945",
      "address": {
        "apartment": "",
        "landmark": "",
        "city": "",
        "name": "asdf",
        "area": "asdf",
        "pincode": "1234",
        "state": "adsf",
        "country": "AX"
      },
      "name": "ayush",
      "billingAddress": [
        {
          "name": "asdf",
          "apartment": "",
          "area": "asdf",
          "pincode": "1234",
          "landmark": "",
          "city": "",
          "state": "adsf",
          "country": "AX",
          "_id": "67a3313db06ceb81ad1a0b35"
        }
      ],
      "shippingAddress": [
        {
          "name": "adsf",
          "apartment": "",
          "area": "sadf",
          "pincode": "5346576",
          "landmark": "",
          "city": "",
          "state": "asdd",
          "country": "HT",
          "_id": "67a3313db06ceb81ad1a0b36"
        }
      ],
      "dateOfBirth": null,
      "location": {}
    }
  },
  "client_info": {
    "deviceType": "desktop"
  },
  "created_at": 1738748264
}
```

**Transaction.failed:** This event is triggered when a transaction is failed from the payment gateway's side.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "transaction.failed",
  "contains": [
    "transaction",
    "user"
  ],
  "payload": {
    "transaction": {
      "_id": "65e01723d03692125f1f3277",
      "status": "FAILED",
      "refundStatus": "NOT_INITIATED",
      "orderId": "",
      "amount": 1,
      "currency": "INR",
      "paymentGateway": "RAZORPAY",
      "paymentId": "",
      "paymentMode": "NETBANKING",
      "createdAt": "2024-02-29T05:33:23.365Z",
      "updatedAt": "2024-02-29T05:33:57.710Z",
      "partialAccess": true,
      "sectionsInclude": [
        "batting"
      ],
      "authorsInclude": [],
      "sectionsExclude": [],
      "authorsExclude": [],
      "tagsInclude": [
        "cricket"
      ],
      "tagsExclude": []
    },
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709184837
}
```


# Login Webhook

The login webhook is used to provide real-time notifications or callbacks related to user login events.

**Login.success:** This event is triggered when the users manage to log in to their account successfully.

```json
{
  "entity": "event",
  "user_id": "65e01719d03692125f1f323f",
  "event": "login.success",
  "contains": [
    "user"
  ],
  "payload": {
    "user": {
      "phoneNumber": "8383884833",
      "email": "fvdzcxz@rsgfdcx.fvc",
      "userId": "65e01719d03692125f1f323f",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "dfsxzc dvzxc",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8383884833"
    }
  },
  "client_info": {
    "userAgent": "axios/0.21.1",
    "country": "India",
    "countryCode": "IN",
    "deviceType": "desktop"
  },
  "created_at": 1709184842
}

```

**Login.failed:** This event is triggered when the users can't log in to their account.

```json
{
  "entity": "event",
  "user_id": "65e026f7d03692125f1f36fa",
  "event": "login.failed",
  "contains": [
    "user"
  ],
  "payload": {
    "user": {
      "phoneNumber": "8943489898",
      "userId": "65e026f7d03692125f1f36fa",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8943489898"
    }
  },
  "client_info": {
    "deviceType": "desktop"
  },
  "created_at": 1709189670
}

```


# Cancel Subscription Webhook

A Cancel Subscription Webhook is used in subscription-based services to notify a system or application when a user cancels their subscription.

```json
{
  "entity": "event",
  "user_id": "65e026f7d03692125f1f36fa",
  "event": "cancelled.subscription",
  "contains": [
    "user",
		"renewal"
  ],
  "payload": {
    "user": {
      "phoneNumber": "8943489898",
      "userId": "65e026f7d03692125f1f36fa",
      "country": "IN",
      "address": {
        "apartment": "",
        "area": "",
        "pincode": "",
        "landmark": "",
        "city": "",
        "state": "",
        "country": ""
      },
      "name": "",
      "city": "new delhi (okhla phase i)",
      "location": {
        "latitude": 28.5223,
        "longitude": 77.2849,
        "postcode": "110001"
      },
      "username": "8943489898"
    },
		"renewal": {
			  "id":  "65df2e5cd821380560e3c5c4",
			  "status": "CANCELLED",
			  "renewalCount": 1,
			  "paymentGatewayPlanId": "P-0EJ04485EU997530NMXPS4WY",
			  "paymentGatewaySubscriptionId": "I-VY5DHGTSMYUR",
			  "price": 13.26,
			  "currency": "USD"
		}
  },
  "client_info": {
    "deviceType": "desktop"
  },
  "created_at": 1709189670
}

```


# Old Webhooks

A webhook is an HTTP-based callback function that allows lightweight, event-driven communication between 2 [application programming interfaces (APIs)](https://www.redhat.com/en/topics/api/what-are-application-programming-interfaces). Webhooks are used by a wide variety of web apps to receive small amounts of data from other apps, but webhooks can also be used to trigger automation workflows in [GitOps](https://www.redhat.com/en/topics/devops/what-is-gitops) environments.

Schema of the payloads of various webhooks supported by Conscent.ai.


# Sign Up Webhook

This event occurs when the user logs in to the platform for the very first time.

You can register your webhook endpoint for receiving ConsCent user data by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook URL from this section. Once the webhook URL is registered and the webhook is in the enabled state - the endpoint will receive user data anytime the user logins in for the first time on the client's website or application via ConsCent.

{% code title="SIGN UP JSON" overflow="wrap" %}

```json
{
  "userName": "9818329028",
  "userId": "7843y9xm44428xm24x2m0x2xm42",
  "freeTrial": true,
  "phoneNumber": "9818329028",
  "email": "test-email@webhook.com",
  "country": "IN",
  "hashedPhoneNumber": "7942mey829mxe1238z2ym9zy39my29zy2z9dy24793msy29z2z",
  "hashedEmail": "8392mx30mx2mu8034x02mx802ry2480nyd249yx420xfn20w4y04xm2024",
  "name": "Test Name",
  "city": "London",
  "location": {
    "latitude": 8359893,
    "longitude": 7438734,
    "postcode": 221993
  },
  "os": "Mac OS 10.16",
  "browser": "Chrome",
  "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36",
  "address": {
    "apartment": "7923492 Apartment1",
    "area": "Test Area",
    "pincode": "389023",
    "landmark": "test landmark",
    "city": "New York City",
    "state": "New York",
    "country": "US"
  },
  "clientTierId": "TestTierID1",
  "clientSpecificUserId": "11003289298"
}
```

{% endcode %}

#### Security:

You will either get the user's email or phoneNumber field and accordingly only one of hashedPhoneNumber or hashedEmail. This hash is generated by using jwt.sign and passing the api secret as the secret. Learn more about jwt here. You can verify this by using jwt.verify for security purposes.

Alternately, you can check the authorization headers. Every request to the webhook uses Basic authorization with the api key as the username and the api secret as the password.

-Do note that you will receive either the phoneNumber or the email depending on what the user chooses to log in with.


# Login Webhook

This event occurs when the user logs in to the platform everytime.

You can register your webhook endpoint for receiving ConsCent user data by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook URL from this section. Once the webhook URL is registered and the webhook is enabled - the endpoint will receive user data (name, email, phone number, hashed email & phone number, city, location, address & country of the user) anytime the user logins in on the client's website or application via Conscent.ai.

{% code title="LOGIN JSON" overflow="wrap" %}

```json
{
  "userName": "9818329028",
  "phoneNumber": "9818329028",
  "email": "test-email@webhook.com",
  "userId": "7843y9xm44428xm24x2m0x2xm42",
  "freeTrial": true,
  "country": "IN",
  "hashedPhoneNumber": "7942mey829mxe1238z2ym9zy39my29zy2z9dy24793msy29z2z",
  "hashedEmail": "8392mx30mx2mu8034x02mx802ry2480nyd249yx420xfn20w4y04xm2024",
  "name": "Test Name",
  "city": "London",
  "location": {
    "latitude": 8359893,
    "longitude": 7438734,
    "postcode": 221993
  },
  "os": "Mac OS 10.16",
  "browser": "Chrome",
  "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36",
  "address": {
    "apartment": "7923492 Apartment1",
    "area": "Test Area",
    "pincode": "389023",
    "landmark": "test landmark",
    "city": "New York City",
    "state": "New York",
    "country": "US"
  },
  "clientTierId": "TestTierID1",
  "clientSpecificUserId": "11003289298"
}
```

{% endcode %}


# Subscription Payment Webhook

This event occurs whenever the user buys any subscription.

You can register your webhook endpoint for receiving ConsCent purchased subscription data by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook URL from this section. Once the webhook URL is registered and the webhook is enabled - the endpoint will receive the user's purchased subscription data anytime the user purchases a subscription on the client's platform or application via ConsCent. Moreover, the webhook is secured by basic auth using the Client's API Key and API Secret provided by ConsCent on the SDK Integration section of the client dashboard - ConsCent Client Integration. You can optionally choose to keep the endpoint protected and authenticate using the provided credentials which are passed in the headers of the POST request to the configured webhook endpoint.

{% code title="SUBSCRIPTION PAYMENT JSON" overflow="wrap" %}

```json
{
  "gstComponents": {
    "physical": 0,
    "digital": 0
  },
  "inrGstComponents": {
    "physical": 0,
    "digital": 0
  },
  "cancelAccess": false,
  "contentType": {
    "digital": true,
    "adFree": false
  },
  "manuallyRenewed": false,
  "renewSubscription": false,
  "availedOffers": [],
  "promotional": false,
  "categories": [],
  "bundle": false,
  "bundleContentIds": [],
  "paymentType": [
    "NEW"
  ],
  "freeTrial": false,
  "migrated": false,
  "partialAccess": true,
  "sectionsInclude": [
    "batting"
  ],
  "authorsInclude": [],
  "sectionsExclude": [],
  "authorsExclude": [],
  "tagsInclude": [
    "cricket"
  ],
  "tagsExclude": [],
  "proRataAppliedPurchases": [],
  "_id": "65d43ad7cc6cfa43c284a06f",
  "userAccount": "65d43ac1cc6cfa43c284a040",
  "clientId": "65015ff10070846629fb981e",
  "paywallId": "65cb7057e57605058015b407",
  "landingPageId": "652e3c6ce7354805632dc7ce",
  "clientContentId": "Client-Story-Id-1",
  "contentId": "650187290070846629fb99d2",
  "buyingPrice": 1900,
  "price": 2000,
  "country": "IN",
  "discountCouponUserId": null,
  "discountCouponTemplateId": null,
  "originalPriceDetails": {
    "currency": "INR"
  },
  "originalInrPrice": 2000,
  "city": "new delhi (okhla phase i)",
  "location": {
    "latitude": 28.5223,
    "longitude": 77.2849,
    "postcode": "110001"
  },
  "userCountry": "IN",
  "expiryDate": "2024-03-20T05:38:21.954Z",
  "priceDetails": {
    "price": 2000,
    "currency": "INR"
  },
  "type": "SUBSCRIPTION",
  "subscriptionTitle": "cricket",
  "operatingSystem": "Mac OS",
  "device": "desktop",
  "subscriptionType": {
    "physical": false,
    "digital": true,
    "adFree": false
  },
  "previouslyPurchasedSubscriptionId": null,
  "subscriptionId": "65c4e2f1f296fa057f3efa9a",
  "tierId": "65c4e2f2f296fa057f3efa9c",
  "subscriptionDetails": {
    "inrPrice": 2000,
    "duration": 1
  },
  "transactionId": "65d43acecc6cfa43c284a06d",
  "bundleSubscriptions": [],
  "createdAt": "2024-02-20T05:38:31.810Z",
  "updatedAt": "2024-02-20T05:38:31.810Z",
  "__v": 0,
  "purchaseId": "65d43ad7cc6cfa43c284a06f",
  "orderId": "order_Nd1NLKC3yN9ERw",
  "renewed": false,
  "chosenTier": {
    "priceOverrides": {
      "country": []
    },
    "currency": "INR",
    "basePrice": 0,
    "offers": [],
    "_id": "65c4e2f2f296fa057f3efa9c",
    "price": 2000,
    "duration": 1,
    "rzpPlanId": "plan_JDJjFwwOG1V8a3"
  },
  "userId": "65d43ac1cc6cfa43c284a040",
  "userEmail": "aksdjl@jkajdlk.com",
  "userPhoneNumber": "9989283898",
  "userName": "kadjlk",
  "userAddress": {
    "apartment": "",
    "area": "",
    "pincode": "",
    "landmark": "",
    "city": "",
    "state": "",
    "country": ""
  },
  "renewedSubscriptionDetails": null
}
```

{% endcode %}

<br>


# Subscription Cancelled Webhook

This event occurs whenever the user cancels the auto renew enabled subscription from ConsCent Dashboard.

You can register your webhook endpoint for receiving data whenever a user cancels their subscription via ConsCent - by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook url from this section. Once the webhook URL is registered and the webhook is in the enabled state - the endpoint will receive the user's canceled subscription data, along with the details of the subscription and the last purchase/renewal of the user for the particular subscription - anytime the user cancels a client's subscription via ConsCent. Moreover, the webhook is secured by basic auth using the Client's API Key and API Secret provided by ConsCent on the SDK Integration section of the client dashboard - ConsCent Client Integration. You can optionally choose to keep the endpoint protected and authenticate using the provided credentials which are passed in the headers of the POST request to the configured webhook endpoint.

{% code title="SUBSCRIPTION CANCELED JSON" overflow="wrap" %}

```json
{
  "cancelledSubscriptionDetails": {
    "renewalCount": 0,
    "rzpSubscriptionId": "sub_InvqpVxG0vu7n8",
    "status": "CANCELLED",
    "price": 300,
    "currency": "INR"
  },
  "userEmail": "admin1@seed.com",
  "userPhoneNumber": "9869779647",
  "userId": "7843y9xm44428xm24x2m0x2xm42",
  "userName": "john doe",
  "userAddress": {
    "apartment": "",
    "area": "",
    "pincode": "",
    "landmark": "",
    "city": "",
    "state": "",
    "country": ""
  },
  "clientSpecificUserId": "11003289298",
  "subscriptionDetails": {
    "freeTrial": {
      "enabled": true,
      "duration": 14
    },
    "recommended": false,
    "benefits": "benefit ewiowe, benefit 2",
    "physical": false,
    "digital": true,
    "enabled": true,
    "migrated": false,
    "couponsEnabled": true,
    "adminCoupon": "",
    "usedCouponNumbers": [1],
    "_id": "616ffd76621d69c5ee43c044",
    "clientId": "601a8ea4f2149f089782814f",
    "title": "Subscription 5",
    "iconUrl": "https://conscent-subscriptions.s3.ap-south-1.amazonaws.com/local/Samakshs-MacBook-Pro-2.local/Screenshot%202021-07-22%20at%209.05.01%20PM.png",
    "tiers": [
      {
        "priceOverrides": {
          "country": []
        },
        "currency": "INR",
        "basePrice": 0,
        "offers": [],
        "_id": "616ffd76621d69c5ee43c045",
        "price": 300,
        "duration": 5
      }
    ],
    "couponCount": 5,
    "createdAt": "2021-10-20T11:28:54.143Z",
    "updatedAt": "2022-01-19T06:45:18.634Z",
    "__v": 5
  },
  "lastPurchaseDetails": {
    "location": {
      "latitude": 13.0411,
      "longitude": 77.5702,
      "postcode": "560056"
    },
    "gstComponents": {
      "physical": 0,
      "digital": 0
    },
    "inrGstComponents": {
      "physical": 0,
      "digital": 0
    },
    "manuallyRenewed": false,
    "renewSubscription": true,
    "availedOffers": [],
    "promotional": false,
    "tags": [],
    "bundle": false,
    "bundleContentIds": [],
    "paymentType": ["REPEAT", "NETWORK"],
    "freeTrial": false,
    "migrated": false,
    "clientId": "601a8ea4f2149f089782814f",
    "buyingPrice": 289.5,
    "price": 300,
    "country": "IN",
    "city": "bengaluru (nagashettyhalli)",
    "userCountry": "IN",
    "expiryDate": "2023-04-25T09:52:52.814Z",
    "priceDetails": {
      "price": 300,
      "currency": "INR"
    },
    "type": "SUBSCRIPTION",
    "subscriptionTitle": "Subscription 5",
    "operatingSystem": "Mac OS",
    "device": "desktop",
    "subscriptionType": {
      "physical": false,
      "digital": true
    },
    "subscriptionId": "616ffd76621d69c5ee43c044",
    "tierId": "616ffd76621d69c5ee43c045",
    "renewalId": "61efc865acb0d82962e2ad14",
    "renewalDetails": {
      "price": 300,
      "currency": "INR"
    }
  }
}
```

{% endcode %}

<br>


# Pass Payment Webhook

This event occurs when the user buys the Pass.

You can register your webhook endpoint for receiving data whenever a user pays for their pass via ConsCent - by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook url from this section. Once the webhook URL is registered and the webhook is in the enabled state - the endpoint will receive the user's pass payment data, along with the details of the pass and the last purchase/renewal of the user for the particular pass - anytime the user purchases a client's pass via ConsCent. Moreover, the webhook is secured by basic auth using the Client's API Key and API Secret provided by ConsCent on the SDK Integration section of the client dashboard - ConsCent Client Integration. You can optionally choose to keep the endpoint protected and authenticate using the provided credentials which are passed in the headers of the POST request to the configured webhook endpoint.

{% code title=" PASS PAYMENT JSON" overflow="wrap" %}

```json
{
  "gstComponents": {
    "physical": 0,
    "digital": 0
  },
  "inrGstComponents": {
    "physical": 0,
    "digital": 0
  },
  "manuallyRenewed": false,
  "renewSubscription": false,
  "availedOffers": [],
  "promotional": false,
  "categories": [],
  "bundle": false,
  "bundleContentIds": [],
  "paymentType": [
    "NEW"
  ],
  "freeTrial": false,
  "migrated": false,
  "_id": "628b76941ed3d9c772be2626",
  "userAccount": "628b765e16d01ac4721e1676",
  "clientId": "5f92a62013332e0f667794dc",
  "clientContentId": "Client-Story-Id-1",
  "contentId": "628b6c2cbf5053737a28a63a",
  "buyingPrice": 80,
  "price": 100,
  "country": "IN",
  "city": "bengaluru (nagashettyhalli)",
  "location": {
    "latitude": 13.0411,
    "longitude": 77.5702,
    "postcode": "560056"
  },
  "userCountry": "IN",
  "expiryDate": "2022-05-23T18:57:07.989Z",
  "passTitle": "qwe",
  "priceDetails": {
    "price": 100,
    "currency": "INR"
  },
  "type": "PASS",
  "operatingSystem": "Mac OS",
  "device": "desktop",
  "createdAt": "2022-05-23T11:57:08.061Z",
  "updatedAt": "2022-05-23T11:57:08.061Z",
  "__v": 0,
  "userId": "628b765e16d01ac4721e1676",
  "userPhoneNumber": "9276278392",
  "userName": "",
  "userAddress": {
    "apartment": "",
    "area": "",
    "pincode": "",
    "landmark": "",
    "city": "",
    "state": "",
    "country": ""
  }
}
```

{% endcode %}


# Subscription Bundle Payment Webhook

This event occurs when the user buys bundle subscription.

You can register your webhook endpoint for receiving data whenever a user pays for their subscription bundle via ConsCent - by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook URL from this section. Once the webhook URL is registered and the webhook is in the enabled state - the endpoint will receive the user's subscription bundle payment data, along with the details of the bundle - anytime the user purchases a client's subscription bundle via ConsCent. Moreover, the webhook is secured by basic auth using the Client's API Key and API Secret provided by ConsCent on the SDK Integration section of the client dashboard - ConsCent Client Integration. You can optionally choose to keep the endpoint protected and authenticate using the provided credentials which are passed in the headers of the POST request to the configured webhook endpoint.

{% code title="Subscription Bundle Payment JSON" overflow="wrap" %}

```json
{
  "purchaseId": "62d02f1bf3299d7b21d4a235",
  "userId": "623b1204ff6e065272e3530b",
  "userEmail": "asd@asd.com",
  "userPhoneNumber": "9876543211",
  "userName": "asdasdasd",
  "userAddress": {
    "state": "SIKKIM",
    "city": "asdsa",
    "area": "asdasdasdas",
    "pincode": "110089"
  },
  "userGender": "MALE",
  "userEmploymentType": "FULL_TIME",
  "utmParameters": {
    "utm_source": "KJ007",
    "utm_medium": "medium",
    "utm_name": "name"
  },
  "bundleBuyingPrice": 332,
  "bundlePrice": 369,
  "bundlePriceDetails": { "price": 369, "currency": "INR" },
  "subscriptionsDetail": [
    {
      "title": "Digital",
      "duration": 1,
      "currencySymbol": "₹",
      "buyingPrice": 90.00,
      "price": "100.00",
      "clientName": "Test Client TSB media venture a",
      "currency": "INR"
    },
    {
      "title": "Digital",
      "duration": 19,
      "currencySymbol": "₹",
      "buyingPrice": 242.10,
      "price": "269.00",
      "clientName": "Test client b",
      "currency": "INR"
    }
  ]
}
```

{% endcode %}


# Review Subscription Webhook

This event occurs just before the user confirms the payment for buying a subscription on the review page.

You can register your webhook endpoint for receiving ConsCent review subscription data i.e.(dropoff users) by logging in to your ConsCent Client Dashboard and navigating to the [Webhook Page](https://client.conscent.in/dashboard/webhook). You will be able to enable/disable and edit your webhook URL from this section. Once the webhook URL is registered and the webhook is in the enabled state - the endpoint will receive the user's review subscription data, anytime the user makes the payment for buying a subscription and comes to the review page on the client's platform or application via ConsCent.The review subscription webhook lets us keep the records of drop-off users. Moreover, the webhook is secured by basic auth using the Client's API Key and API Secret provided by ConsCent on the SDK Integration section of the client dashboard - [ConsCent Client Integration](https://client.conscent.in/dashboard/integration). You can optionally choose to keep the endpoint protected and authenticate using the provided credentials which are passed in the headers of the POST request to the configured webhook endpoint.

{% code title="Review Subscription JSON" overflow="wrap" %}

```json
{
   "phoneNumber": "9847598673",
  "userId": "6345116cb9beaf3033c065cc",
  "country": "IN",
  "hashedPhoneNumber": "eyJhbGciOiJIUzI1NiJ9.OTg0NzU5ODY3Mw.7tvT8abeu_sGEWSfKdgYRRo7oZ65qBwatyFIF1VOhGY",
  "address": {
    "apartment": "",
    "area": "",
    "pincode": "",
    "landmark": "",
    "city": "",
    "state": "",
    "country": ""
  },
  "name": "",
  "city": "defence colony",
  "location": {
    "latitude": 28.5714,
    "longitude": 77.2327
  },
  "browser": "Chrome",
  "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
  "os": "Mac OS",
  "username": "9847598673",
  "subscriptionDetails": {
    "subscriptionId": "61e951161a563d0729652d21",
    "tierId": "61e951161a563d0729652d23",
    "title": "AD Free",
    "price": 600,
    "currency": "INR"
  }
}
```

{% endcode %}


# Micro Payment Webhook

This event occurs when the user makes the payment for per article/content.

You can register your webhook endpoint for receiving ConsCent purchased content data by logging in to your ConsCent Client Dashboard and navigating to the Webhook Page. You will be able to enable/disable and edit your webhook URL from this section. Once the webhook URL is registered and the webhook is in the enabled state - the endpoint will receive the user's purchased content data anytime the user purchases any content on the client's platform or application via ConsCent. Moreover, the webhook is secured by basic auth using the Client's API Key and API Secret provided by ConsCent on the SDK Integration section of the client dashboard - ConsCent Client Integration. You can optionally choose to keep the endpoint protected and authenticate using the provided credentials which are passed in the headers of the POST request to the configured webhook endpoint.

{% code title="Micro Payment JOSN" overflow="wrap" %}

```json
{
  "gstComponents": {
    "physical": 0,
    "digital": 0
  },
  "inrGstComponents": {
    "physical": 0,
    "digital": 0
  },
  "contentType": {
    "digital": true,
    "adFree": false
  },
  "categories": [],
  "bundle": false,
  "bundleContentIds": [],
  "paymentType": [
    "REPEAT"
  ],
  "migrated": false,
  "_id": "6437ade44c60bc0552ad3477",
  "userAccount": "642ed4902107e35b19bf29fa",
  "clientId": "5f92a62013332e0f667794dc",
  "paywallId": "6435427bb0658c70abe7d18d",
  "clientContentId": "Client-Story-Id-4",
  "contentId": "61fa72efb76afa4ce17fde95",
  "buyingPrice": 79.2,
  "price": 99,
  "country": "IN",
  "city": "deoli",
  "location": {
    "latitude": 28.5025,
    "longitude": 77.2312
  },
  "userCountry": "IN",
  "expiryDate": "2023-04-20T07:23:16.810Z",
  "priceDetails": {
    "price": 99,
    "currency": "INR"
  },
  "type": "CONTENT",
  "operatingSystem": "Mac OS",
  "device": "desktop",
  "createdAt": "2023-04-13T07:23:16.829Z",
  "updatedAt": "2023-04-13T07:23:16.829Z",
  "__v": 0,
  "userId": "642ed4902107e35b19bf29fa",
  "userPhoneNumber": "9488298324",
  "userName": "",
  "userAddress": {
    "apartment": "",
    "area": "",
    "pincode": "",
    "landmark": "",
    "city": "",
    "state": "",
    "country": ""
  }
}
```

{% endcode %}


# How to validate Webhooks?

When your webhook `secret` is set, Conscent uses it to create a hash signature with each payload. This hash signature is passed with each request under the `X-Conscent-Signature` header that you need to validate at your end.

{% tabs %}
{% tab title="Nodejs" %}

```javascript
var crypto = require('crypto');

var hmac = crypto.createHmac('sha256', '<WEBHOOK_SECRET>');

//passing the data to be hashed
rawBody = '<RAW_BODY_OF_REQUEST>';
signature = hmac.update(req.body).digest('hex');

//Printing the output on the console
console.log('hmac : ' + signature);

// NOTE: try matching `signature` with request header `x-conscent-signature`
```

{% endtab %}
{% endtabs %}

> ```
> Do Not Parse or Cast the Webhook Request Body
>
> While generating the signature at your end, ensure that the webhook body passed as an argument is the raw webhook request body. Do not parse or cast the webhook request body.
> ```


# Registering The Content

* This endpoint allows you to register your content on Conscent.ai - with the Content Title, ContentId, Content URL, categories, tags, sections, analytics pixels (Facebook and Google), Price, and any specific price overrides for a different country.
* Moreover, you can also set the content duration- meaning that if a user purchases the content on Conscent.ai, then that user can have free access to the content for {duration} amount of time.
* By default, we use a 1 Day duration. Moreover, the ContentType field is optional - and if no 'contentType' is provided, then the default 'contentType' of the Client will be treated as the 'contentType' of the content being registered.


# Create Content

This section lets you register the content on Conscent.ai.

## Authorization

<mark style="color:green;">`POST`</mark> `{API_URL}/content`

Client API Key and API Secret must be passed in Authorization Headers using Basic Auth. With API Key as the Username and API Secret as the password.

#### Request Body

| Name                                        | Type                       | Description               |
| ------------------------------------------- | -------------------------- | ------------------------- |
| contentId<mark style="color:red;">\*</mark> | String                     | Content Id of the content |
| price                                       | Integer                    | price of the content      |
| categories                                  | \["category1","category2"] |                           |
| authorId                                    | String                     |                           |
| sections                                    | \["section1","section2"]   |                           |
| tags                                        | \["tag1","tag2"]           |                           |
| title<mark style="color:red;">\*</mark>     | String                     | Title of the content      |
| url<mark style="color:red;">\*</mark>       | String                     | url of the content        |
| contentType                                 | String                     |                           |
| currency                                    | String                     |                           |
| duration                                    | Integer                    | duration of the content   |

{% tabs %}
{% tab title="201: Created { "message": "New Content Created!"}" %}

{% endtab %}
{% endtabs %}

> To pick the Default Price and Default Duration for micropayment, you need to set them [here](https://client.conscent.in/client/dashboard/micropayments) and pass "price" : null and "duration" : null while registering the content.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2F9hqKqH7H9ZhhEawRTzLV%2FScreenshot%202023-05-29%20at%2010.57.28%20AM.png?alt=media&amp;token=69fcb317-22a1-4da9-8d73-0a74ac8cd34b" alt="" width="375"><figcaption></figcaption></figure>

{% tabs %}
{% tab title="shell" %}

```
 curl -X POST '{API_URL}/api/v1/content/' \
-H 'Authorization: Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==' \
-H 'Content-Type: application/json' \
-d '{
 "contentId" : "testingID For Client Content",
    "duration": 30,
    "title": "Test content for API functionality",
    "price": 1,
    "currency": "INR",
    "categories": ["category1", "category2"],
    "tags": ["free", "premium", "metered"],
    "sections": ["EDITORIAL"],
    "authorId": "7589",
    "contentType": "STORY",
    "url": "www.google.com",
    "priceOverrides": {
        "country": [
            {
                "name": "GL",
                "price": 3
            },
            {
                "name": "IN",
                "price": 5
            },
            {
                "name": "US",
                "price": 7
            }
        ]
    },
    "download": {
      "url": "https://yourdownloadurl.com",
      "fileName": "Download File - Name",
      "fileType": "PDF"
    },
    "pixels": {
        "facebook": {
            "pixelId": "98357934724994",
            "events": [
                {
                    "eventType": "VIEW",
                    "name": "PageView"
                },
                {
                    "eventType": "CONVERSION",
                    "name": "Purchase",
                    "data": {
                        "value": "dataValue"
                    }
                }
            ]
        },
        "google": {
            "trackingId": "G-RJDY8493"
        }
    }
}'
```

The above command returns JSON structured like this:

```json
{
    "message": "New Content Created!",
    "content": {
        "title": "Test content for API functionality",
        "price": 1,
        "currency": "INR",
        "contentId": "898",
        "duration": 30,
        "url": "www.google.com",
        "contentType": "STORY",
        "authorId": "7589",
        "priceOverrides": {
            "country": [
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b4",
                    "name": "GL",
                    "price": 3
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b5",
                    "name": "IN",
                    "price": 5
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b6",
                    "name": "US",
                    "price": 7
                }
            ]
        },
        "download": {
            "url": "https://www.google.com",
            "fileName": "Download File - Name",
            "fileType": "PDF",
            "s3Key": "stage/Demo Client/Download File - Name-898.pdf"
        },
        "pixels": {
            "facebook": {
                "pixelId": "98357934724994",
                "events": [
                    {
                        "eventType": "VIEW",
                        "name": "PageView"
                    },
                    {
                        "eventType": "CONVERSION",
                        "name": "Purchase",
                        "data": {
                            "value": "dataValue"
                        }
                    }
                ]
            },
            "google": {
                "trackingId": "G-RJDY8493"
            }
        },
        "categories": [
            "category1",
            "category2"
        ],
        "publicationDate": null,
        "tags": [
            "free",
            "premium",
            "metered"
        ],
        "sections": [
            "EDITORIAL"
        ]
    }
}
```

{% endtab %}

{% tab title="javaScript" %}

```
var axios = require("axios");
var data = JSON.stringify({
  contentId: "testingID For Client",
  duration: 30,
  title: "Test content for API functionality",
  price: 1,
  currency: "INR",
  url: "www.google.com",
  contentType: "STORY",
  categories: ["category1", "category2"],
  tags: ["entertainment", "sports"],
  sections: ["EDITORIAL"],
  authorId: "7589",
  priceOverrides: {
    country: [
      { name: "GL", price: 3 },
      { name: "IN", price: 5 },
      { name: "US", price: 7 },
    ],
  },
  download: {
    url: "https://yourdownloadurl.com",
    fileName: "Download File - Name",
    fileType: "PDF",
  },
  pixels: {
    facebook: {
      pixelId: "98357934724994",
      events: [
        {
          eventType: "VIEW",
          name: "PageView",
        },
        {
          eventType: "CONVERSION",
          name: "Purchase",
          data: {
            value: "dataValue",
          },
        },
      ],
    },
    google: {
      trackingId: "G-RJDY8493",
    },
  },
});

var config = {
  method: "post",
  url: "{API_URL}/api/v1/content/",
  headers: {
    Authorization:
      "Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==",
    "Content-Type": "application/json",
  },
  data: data,
};

axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });
```

The above command returns JSON structured like this:

```json
{
    "message": "New Content Created!",
    "content": {
        "title": "Test content for API functionality",
        "price": 1,
        "currency": "INR",
        "contentId": "898",
        "duration": 30,
        "url": "www.google.com",
        "contentType": "STORY",
        "authorId": "7589",
        "priceOverrides": {
            "country": [
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b4",
                    "name": "GL",
                    "price": 3
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b5",
                    "name": "IN",
                    "price": 5
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b6",
                    "name": "US",
                    "price": 7
                }
            ]
        },
        "download": {
            "url": "https://www.google.com",
            "fileName": "Download File - Name",
            "fileType": "PDF",
            "s3Key": "stage/Demo Client/Download File - Name-898.pdf"
        },
        "pixels": {
            "facebook": {
                "pixelId": "98357934724994",
                "events": [
                    {
                        "eventType": "VIEW",
                        "name": "PageView"
                    },
                    {
                        "eventType": "CONVERSION",
                        "name": "Purchase",
                        "data": {
                            "value": "dataValue"
                        }
                    }
                ]
            },
            "google": {
                "trackingId": "G-RJDY8493"
            }
        },
        "categories": [
            "category1",
            "category2"
        ],
        "publishedAt": null,
        "tags": [
            "free",
            "premium",
            "metered"
        ],
        "sections": [
            "EDITORIAL"
        ]
    }
}
```

{% endtab %}

{% tab title="php" %}

```
       $curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "{API_URL}/api/v1/content/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS =>'{
    "contentId" : "testingID For Client Content",
    "duration" : 30,
    "title" : "Test content for API functionality",
    "price" : 1,
    "currency": "INR",
    "url": "www.google.com",
    "contentType": "STORY",
    "categories": ["category1", "category2"],
    "tags": ["entertainment", "sports"],
    "sections": ["EDITORIAL"],
    "authorId": "7589",
    "priceOverrides": {
        "country": [
            {
                "name": "GL",
                "price": 3
            },
            {
                "name": "IN",
                "price": 5
            },
            {
                "name": "US",
                "price": 7
            }
        ]
    },
    "download": {
      "url": "https://yourdownloadurl.com",
      "fileName": "Download File - Name",
      "fileType": "PDF"
    },
    "pixels": {
       "facebook": {
            "pixelId": "98357934724994",
            "events": [
                {
                    "eventType": "VIEW",
                    "name": "PageView"
                },
                {
                    "eventType": "CONVERSION",
                    "name": "Purchase",
                    "data": {
                        "value": "dataValue"
                    }
                }
            ]
        },
        "google": {
            "trackingId": "G-RJDY8493"
        }
    }
  }',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
```

The above command returns JSON structured like this:

```json
{
    "message": "New Content Created!",
    "content": {
        "title": "Test content for API functionality",
        "price": 1,
        "currency": "INR",
        "contentId": "898",
        "duration": 30,
        "url": "www.google.com",
        "contentType": "STORY",
        "authorId": "7589",
        "priceOverrides": {
            "country": [
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b4",
                    "name": "GL",
                    "price": 3
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b5",
                    "name": "IN",
                    "price": 5
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b6",
                    "name": "US",
                    "price": 7
                }
            ]
        },
        "download": {
            "url": "https://www.google.com",
            "fileName": "Download File - Name",
            "fileType": "PDF",
            "s3Key": "stage/Demo Client/Download File - Name-898.pdf"
        },
        "pixels": {
            "facebook": {
                "pixelId": "98357934724994",
                "events": [
                    {
                        "eventType": "VIEW",
                        "name": "PageView"
                    },
                    {
                        "eventType": "CONVERSION",
                        "name": "Purchase",
                        "data": {
                            "value": "dataValue"
                        }
                    }
                ]
            },
            "google": {
                "trackingId": "G-RJDY8493"
            }
        },
        "categories": [
            "category1",
            "category2"
        ],
        "publishedAt": null,
        "tags": [
            "free",
            "premium",
            "metered"
        ],
        "sections": [
            "EDITORIAL"
        ]
    }
}
```

{% endtab %}
{% endtabs %}


# Edit Content

This section lets you edit the content.

## Authorization

<mark style="color:purple;">`PATCH`</mark> `{API_URL}/content/{contentId}`

Client API Key and API Secret must be passed in Authorization Headers using Basic Auth. With API Key as the Username and API Secret as the password.

#### Path Parameters

| Name                                        | Type   | Description                            |
| ------------------------------------------- | ------ | -------------------------------------- |
| contentId<mark style="color:red;">\*</mark> | String | The ID of the Content you wish to edit |

#### Request Body

| Name      | Type    | Description              |
| --------- | ------- | ------------------------ |
| title     | String  | Title of the content     |
| contentId | String  | contentId of the content |
| duration  | Integer | duration of the content  |
| priv      |         | price of the content     |
| url       | String  | URL of the content       |

{% tabs %}
{% tab title="200: OK { "message": "Content Edited Successfully"}" %}

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="shell" %}

```
curl -X PATCH '{API_URL}/api/v1/content/{contentId}' \
-H 'Authorization: Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==' \
-H 'Content-Type: application/json' \
-d '{
    "contentId" : "testingID For Client Content",
    "duration" : 30,
    "title" : "Test content for API functionality Edited",
    "price" : 90,
    "currency": "INR",
    "categories": ["category1", "category2"],
    "tags": ["free", "premium", "metered"],
    "sections": ["EDITORIAL"],
    "authorId": "7589",
    "url": "www.google.com",
    "contentType": "PREMIUM CONTENT",
    "priceOverrides": {
        "country": [
            {
                "name": "GL",
                "price": 2
            },
            {
                "name": "IN",
                "price": 1
            },
            {
                "name": "US",
                "price": 0
            }
        ]
    },
    "download": {
      "url": "https://yourdownloadurl.com",
      "fileName": "Download File - Edited Name",
      "fileType": "PDF"
    },
    "pixels": {
        "facebook": {
            "pixelId": "98357934724994",
            "events": [
                {
                    "eventType": "VIEW",
                    "name": "PageView"
                },
                {
                    "eventType": "CONVERSION",
                    "name": "Purchase",
                    "data": {
                        "value": "dataValue"
                    }
                }
            ]
        },
        "google": {
            "trackingId": "G-RJDY8493"
        }
    }
}'

```

The above command returns JSON structured like this:

```json
{
    "message": "Content Edited Successfully",
    "editedContent": {
        "title": "Test content for API functionality",
        "contentId": "898",
        "price": 90,
        "currency": "INR",
        "duration": 30,
        "url": "www.google.com",
        "contentType": "STORY",
        "authorId": "7589",
        "priceOverrides": {
            "country": [
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b4",
                    "name": "GL",
                    "price": 3
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b5",
                    "name": "IN",
                    "price": 5
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b6",
                    "name": "US",
                    "price": 7
                }
            ]
        },
        "download": {
            "url": "https://www.google.com",
            "fileName": "Download File - Name",
            "fileType": "PDF",
            "s3Key": "stage/Demo Client/Download File - Name-898.pdf"
        },
        "pixels": {
            "facebook": {
                "pixelId": "98357934724994",
                "events": [
                    {
                        "eventType": "VIEW",
                        "name": "PageView"
                    },
                    {
                        "eventType": "CONVERSION",
                        "name": "Purchase",
                        "data": {
                            "value": "dataValue"
                        }
                    }
                ]
            },
            "google": {
                "trackingId": "G-RJDY8493"
            }
        },
        "categories": [
            "category1",
            "category2"
        ],
        "tags": [
            "free",
            "premium",
            "metered"
        ],
        "sections": [
            "EDITORIAL"
        ],
        "publicationDate": null
    }
}
```

{% endtab %}

{% tab title="javaScript" %}

```
var axios = require("axios");
var data = JSON.stringify({
  contentId: "testingID For Client Content",
  duration: 30,
  title: "Test content for API functionality Edited",
  price: 90,
  currency: "INR",
  categories: ["category1", "category2"],
  tags: ["entertainment", "sports"],
  sections: ["EDITORIAL"],
  authorId: "7589",
  url: "www.google.com",
  contentType: "PREMIUM CONTENT",
  priceOverrides: {
    country: [
      { name: "GL", price: 2 },
      { name: "IN", price: 1 },
      { name: "US", price: 0 },
    ],
  },
  download: {
    url: "https://yourdownloadurl.com",
    fileName: "Download File - Edited Name",
    fileType: "PDF",
  },
  pixels: {
    facebook: {
      pixelId: "98357934724994",
      events: [
        {
          eventType: "VIEW",
          name: "PageView",
        },
        {
          eventType: "CONVERSION",
          name: "Purchase",
          data: {
            value: "dataValue",
          },
        },
      ],
    },
     google: {
      trackingId: "G-RJDY8493",
    },
  },
});

var config = {
  method: "patch",
  url: "{API_URL}/api/v1/content/{contentId}",
  headers: {
    Authorization:
      "Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWjnJL877NJSjnkHSk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==",
    "Content-Type": "application/json",
  },
  data: data,
};

axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });
```

The above command returns JSON structured like this:

```json
{
    "message": "Content Edited Successfully",
    "editedContent": {
        "title": "Test content for API functionality",
        "contentId": "898",
        "price": 90,
        "currency": "INR",
        "duration": 30,
        "url": "www.google.com",
        "contentType": "STORY",
        "authorId": "7589",
        "priceOverrides": {
            "country": [
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b4",
                    "name": "GL",
                    "price": 3
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b5",
                    "name": "IN",
                    "price": 5
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b6",
                    "name": "US",
                    "price": 7
                }
            ]
        },
        "download": {
            "url": "https://www.google.com",
            "fileName": "Download File - Name",
            "fileType": "PDF",
            "s3Key": "stage/Demo Client/Download File - Name-898.pdf"
        },
        "pixels": {
            "facebook": {
                "pixelId": "98357934724994",
                "events": [
                    {
                        "eventType": "VIEW",
                        "name": "PageView"
                    },
                    {
                        "eventType": "CONVERSION",
                        "name": "Purchase",
                        "data": {
                            "value": "dataValue"
                        }
                    }
                ]
            },
            "google": {
                "trackingId": "G-RJDY8493"
            }
        },
        "categories": [
            "category1",
            "category2"
        ],
        "tags": [
            "free",
            "premium",
            "metered"
        ],
        "sections": [
            "EDITORIAL"
        ],
        "publishedAt": null
    }
}
```

{% endtab %}

{% tab title="php" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "{API_URL}/api/v1/content/Client%20Content%20Id%2011",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PATCH",
   CURLOPT_POSTFIELDS =>'{
    "contentId" : "testingID For Client Content",
    "duration": 30,
    "title": "Test content for API functionality Edited",
    "price" : 90,
    "currency": "INR",
    "url": "www.google.com",
    "contentType": "PREMIUM CONTENT",
    "categories": ["category3"],
    "priceOverrides": {
        "country": [
            {
                "name": "GL",
                "price": 2
            },
            {
                "name": "IN",
                "price": 1
            },
            {
                "name": "US",
                "price": 0
            }
        ]
    },
    "download": {
      "url": "https://yourdownloadurl.com",
      "fileName": "Download File - Edited Name",
      "fileType": "PDF"
    },
    "pixels": {
    "facebook": {
            "pixelId": "98357934724994",
            "events": [
                {
                    "eventType": "VIEW",
                    "name": "PageView"
                },
                {
                    "eventType": "CONVERSION",
                    "name": "Purchase",
                    "data": {
                        "value": "dataValue"
                    }
                }
            ]
        },
        "google": {
            "trackingId": "G-RJDY8493"
        }
    }
}',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

The above command returns JSON structured like this:

```json
{
    "message": "Content Edited Successfully",
    "editedContent": {
        "title": "Test content for API functionality",
        "contentId": "898",
        "price": 90,
        "currency": "INR",
        "duration": 30,
        "url": "www.google.com",
        "contentType": "STORY",
        "authorId": "7589",
        "priceOverrides": {
            "country": [
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b4",
                    "name": "GL",
                    "price": 3
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b5",
                    "name": "IN",
                    "price": 5
                },
                {
                    "currency": "INR",
                    "_id": "605b25824646e9233aef61b6",
                    "name": "US",
                    "price": 7
                }
            ]
        },
        "download": {
            "url": "https://www.google.com",
            "fileName": "Download File - Name",
            "fileType": "PDF",
            "s3Key": "stage/Demo Client/Download File - Name-898.pdf"
        },
        "pixels": {
            "facebook": {
                "pixelId": "98357934724994",
                "events": [
                    {
                        "eventType": "VIEW",
                        "name": "PageView"
                    },
                    {
                        "eventType": "CONVERSION",
                        "name": "Purchase",
                        "data": {
                            "value": "dataValue"
                        }
                    }
                ]
            },
            "google": {
                "trackingId": "G-RJDY8493"
            }
        },
        "categories": [
            "category1",
            "category2"
        ],
        "tags": [
            "free",
            "premium",
            "metered"
        ],
        "sections": [
            "EDITORIAL"
        ],
        "publishedAt": null
    }
}
```

{% endtab %}
{% endtabs %}


# View Content

This section lets you get all the content registered on Conscent.ai.

## Authorization

<mark style="color:blue;">`GET`</mark> `{{API_URL}}/content/client`

Client API Key and Secret must be passed in Authorization Headers using Basic Auth. With API Key as the Username and API Secret as the password.

#### Query Parameters

| Name       | Type    | Description                                                                                                                                                        |
| ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| pageNumber | Integer | Pagination Parameters - which page of the contents list you would like to retrieve (default = 1). Since each page will have 20 (default) individual contents ONLY. |
| pageSize   | Integer | Pagination Parameters - the number of individual contents to retrieve on each page (default = 20).                                                                 |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="shell" %}

```
curl -X GET '{API_URL}/api/v1/content/client' \
-H 'Authorization: Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw=='
```

{% endtab %}

{% tab title="javaScript" %}

```
var axios = require("axios");

var config = {
  method: "get",
  url: "{API_URL}/api/v1/content/client",
  headers: {
    Authorization:
      "Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw==",
  },
};

axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });
```

{% endtab %}

{% tab title="php" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "{API_URL}/api/v1/content/client",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Basic RDZXN1Y4US1NTkc0V1lDLVFYOUJQMkItOEU3QjZLRzpUNFNHSjlISDQ3TVpRWkdTWkVGVjZYUk5TS1E4RDZXN1Y4UU1ORzRXWUNRWDlCUDJCOEU3QjZLRw=="
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;


```

{% endtab %}
{% endtabs %}

The above command returns JSON structured like this:

```json
{
    "content": [
        {
            "title": "Tastiest ice creams",
            "contentId": "Client Story Id 2",
            "price": 12,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://www.anish.com",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "imageUrl": "https://www.google.com/logos/doodles/2022/get-vaccinated-wear-a-mask-save-lives-january-20-copy-6753651837109686-2xa.gif",
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Coolest superheroes",
            "contentId": "Client Story Id 3",
            "price": 10,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://www.google.com",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "imageUrl": "https://www.google.com/logos/doodles/2022/get-vaccinated-wear-a-mask-save-lives-january-20-copy-6753651837109686-2xa.gif",
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Best of netflix",
            "contentId": "Client Story Id 4",
            "price": 1,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://www.google.com",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "imageUrl": "https://www.google.com/logos/doodles/2022/get-vaccinated-wear-a-mask-save-lives-january-19-copy-6753651837109685-2xa.gif",
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Depths of the Ocean",
            "contentId": "Client Story Id 9",
            "price": 0.01,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://www.google.com",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Test story for API functionality",
            "contentId": "testingID31",
            "price": 0.1,
            "currency": "INR",
            "contentType": null,
            "duration": 2,
            "url": "https://www.anish.com",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [
                "anish"
            ],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "apple",
            "contentId": "apple",
            "price": 10,
            "currency": "INR",
            "contentType": null,
            "duration": 5,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/apple",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "imageUrl": null,
            "tags": [
                "games",
                "sports"
            ],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "mango",
            "contentId": "mango",
            "price": 10,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/mango",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "imageUrl": null,
            "tags": [
                "b",
                "apple",
                "goa",
                "gannn"
            ],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Client Story Id 5",
            "contentId": "Client Story Id 5",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client%2520Story%2520Id%25205",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "banana\n",
            "contentId": "banana\n",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/banana",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "banana ",
            "contentId": "banana ",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/banana",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "content 1",
            "contentId": "content1",
            "price": 1,
            "currency": "INR",
            "contentType": null,
            "duration": 2,
            "url": "www.google.com",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "banana",
            "contentId": "banana",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/banana",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Client%20Story%20Id%205",
            "contentId": "Client%20Story%20Id%205",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client%252520Story%252520Id%2525205",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "garden",
            "contentId": "garden",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/garden",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "eden",
            "contentId": "eden",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/eden",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "wight",
            "contentId": "wight",
            "price": null,
            "currency": "INR",
            "contentType": null,
            "duration": 1,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/wight",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Client Story Id 3",
            "contentId": "Client%20Story%20Id%203",
            "price": null,
            "currency": null,
            "contentType": null,
            "duration": null,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client%20Story%20Id%203",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Client Story Id 4",
            "contentId": "Client%20Story%20Id%204",
            "price": null,
            "currency": null,
            "contentType": null,
            "duration": null,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client%20Story%20Id%204",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "Client Story Id 2",
            "contentId": "Client%20Story%20Id%202",
            "price": null,
            "currency": null,
            "contentType": null,
            "duration": null,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Client%20Story%20Id%202",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        },
        {
            "title": "can u play?",
            "contentId": "Story Id 1",
            "price": null,
            "currency": null,
            "contentType": null,
            "duration": null,
            "url": "https://csc-mock.netlify.app/5f92a62013332e0f667794dc/Story%20Id%201",
            "download": {},
            "bundleContentIds": [],
            "pixels": {
                "facebook": {
                    "events": []
                },
                "google": {}
            },
            "excludeFromSubscription": false,
            "categories": [],
            "tags": [],
            "sections": [],
            "publicationDate": null
        }
    ],
    "pagination": {
        "pageNumber": 1,
        "pageSize": 20,
        "totalRecords": 210,
        "totalPages": 11
    }
}
```

*To retrieve the details of one content at a time - Pass the clientContentId after client.*

*<mark style="color:orange;">{{BASE\_URL}}/content/client/Client Story Id 2</mark>*


# Country Code List

<table><thead><tr><th width="418.5">COUNTRY NAME</th><th>COUNTRY CODE</th></tr></thead><tbody><tr><td><p>Afghanistan </p><p>Åland Islands </p><p>Albania </p><p>Algeria</p><p>American Samoa</p><p>Andorra</p><p>Angola</p><p>Anguilla</p><p>Antarctica</p><p>Antigua and Barbuda</p><p>Argentina</p><p>Armenia</p><p>Aruba </p><p>Australia </p><p>Austria</p><p>Azerbaijan</p></td><td><p>AF</p><p>AX</p><p>AL</p><p>DZ</p><p>AS</p><p>AD</p><p>AO</p><p>AI</p><p>AQ</p><p>AG</p><p>AR</p><p>AM</p><p>AW</p><p>AU</p><p>AT</p><p>AZ</p></td></tr><tr><td><p>Bahrain</p><p>Bahamas</p><p>Bangladesh</p><p>Barbados</p><p>Belarus</p><p>Belgium</p><p>Belize</p><p>Benin</p><p>Bermuda </p><p>Bhutan </p><p>Bolivia, Plurinational State of </p><p>Bonaire, Sint Eustatius and Saba </p><p>Bosnia and Herzegovina </p><p>Botswana </p><p>Bouvet Island </p><p>Brazil </p><p>British Indian Ocean Territory </p><p>Brunei Darussalam </p><p>Bulgaria</p><p>Burkina Faso</p><p>Burundi </p></td><td><p>BH</p><p>BS</p><p>BD</p><p>BB</p><p>BY</p><p>BE</p><p>BZ</p><p>BJ</p><p>BM</p><p>BT</p><p>BO</p><p>BQ</p><p>BA</p><p>BW</p><p>BV</p><p>BR</p><p>IO</p><p>BN</p><p>BG</p><p>BF</p><p>BI</p></td></tr><tr><td><p>Cambodia</p><p>Cameroon </p><p>Canada</p><p>Cape Verde </p><p>Cayman Islands </p><p>Central African Republic</p><p>Chad</p><p>Chile</p><p>China</p><p>Christmas Island</p><p>Cocos (Keeling) Islands</p><p>Colombia</p><p>Comoros</p><p>Congo</p><p>Congo, the Democratic Republic of the</p><p>Cook Islands</p><p>Costa Rica</p><p>Côte d'Ivoire</p><p>Croatia</p><p>Cuba</p><p>Curaçao</p><p>Cyprus</p><p>Czech Republic</p></td><td><p>KH</p><p>CM</p><p>CA</p><p>CV</p><p>KY</p><p>CF</p><p>TD</p><p>CL</p><p>CN</p><p>CX</p><p>CC</p><p>CO</p><p>KM</p><p>CG</p><p>CD</p><p>CK</p><p>CR</p><p>CI</p><p>HR</p><p>CU</p><p>CW</p><p>CY</p><p>CZ</p></td></tr><tr><td><p>Denmark</p><p>Djibouti </p><p>Dominica </p><p>Dominican Republic</p></td><td><p>DK</p><p>DJ</p><p>DM</p><p>DO</p></td></tr><tr><td><p>Ecuador</p><p>Egypt</p><p>El Salvador</p><p>Equatorial Guinea</p><p>Eritrea</p><p>Estonia</p><p>Ethiopia</p></td><td><p>EC</p><p>EG</p><p>SV</p><p>GQ</p><p>ER</p><p>EE</p><p>ET</p></td></tr><tr><td><p>Falkland Islands (Malvinas)</p><p>Faroe Islands</p><p>Fiji</p><p>Finland</p><p>France</p><p>French Guiana</p><p>French Polynesia</p><p>French Southern Territories</p></td><td><p>FK</p><p>FO</p><p>FJ</p><p>FI</p><p>FR</p><p>GF</p><p>PF</p><p>TF</p></td></tr><tr><td><p>Gabon </p><p>Gambia </p><p>Georgia </p><p>Germany </p><p>Ghana </p><p>Gibraltar </p><p>Greece </p><p>Greenland </p><p>Grenada</p><p>Guadeloupe </p><p>Guam </p><p>Guatemala </p><p>Guernsey </p><p>Guinea </p><p>Guinea-Bissau </p><p>Guyana </p></td><td><p>GA</p><p>GM</p><p>GE</p><p>DE</p><p>GH</p><p>GI</p><p>GR</p><p>GL</p><p>GD</p><p>GP</p><p>GU</p><p>GT</p><p>GG</p><p>GN</p><p>GW</p><p>GY</p></td></tr><tr><td><p>Haiti</p><p>Heard Island and McDonald Islands  </p><p>Holy See (Vatican City State)</p><p>Honduras </p><p>Hong Kong </p><p>Hungary </p></td><td><p>HT</p><p>HM</p><p>VA</p><p>HN</p><p>HK</p><p>HU</p></td></tr><tr><td><p>Iceland</p><p>India</p><p>Indonesia</p><p>Iran, Islamic Republic of</p><p>Iraq</p><p>Ireland</p><p>Isle of Man</p><p>Israel</p><p>Italy</p></td><td><p>IS</p><p>IN</p><p>ID</p><p>IR</p><p>IQ</p><p>IE</p><p>IM</p><p>IL</p><p>IT</p></td></tr><tr><td><p>Jamaica</p><p>Japan </p><p>Jersey </p><p>Jordan </p></td><td><p>JM</p><p>JP</p><p>JE</p><p>JO</p></td></tr><tr><td><p>Kazakhstan</p><p>Kenya</p><p>Kiribati </p><p>Korea, Democratic People's Republic of </p><p>Korea, Republic of</p><p>Kuwait </p><p>Kyrgyzstan </p></td><td><p>KZ</p><p>KE</p><p>KI</p><p>KP</p><p>KR</p><p>KW</p><p>KG</p></td></tr><tr><td><p>Lao People's Democratic Republic </p><p>Latvia </p><p>Lebanon </p><p>Lesotho</p><p>Liberia </p><p>Libya </p><p>Liechtenstein </p><p>Lithuania</p><p>Luxembourg </p></td><td><p>LA</p><p>LV</p><p>LB</p><p>LS</p><p>LR</p><p>LY</p><p>LI</p><p>LT</p><p>LU</p></td></tr><tr><td><p>Macao </p><p>Macedonia, the Former Yugoslav Republic of </p><p>Madagascar</p><p>Malawi </p><p>Malaysia </p><p>Maldives</p><p>Mali</p><p>Malta</p><p>Marshall Islands</p><p>Martinique</p><p>Mauritania </p><p>Mauritius </p><p>Mayotte </p><p>Mexico </p><p>Micronesia, Federated States of </p><p>Moldova, Republic of </p><p>Monaco </p><p>Mongolia </p><p>Montenegro </p><p>Montserrat </p><p>Morocco </p><p>Mozambique </p><p>Myanmar</p></td><td><p>MO</p><p>MK</p><p>MG</p><p>MW</p><p>MY</p><p>MV</p><p>ML</p><p>MT</p><p>MH</p><p>MQ</p><p>MR</p><p>MU</p><p>YT</p><p>MX</p><p>FM</p><p>MD</p><p>MC</p><p>MN</p><p>ME</p><p>MS</p><p>MA</p><p>MZ</p><p>MM</p></td></tr><tr><td><p>Namibia </p><p>Nauru </p><p>Nepal </p><p>Netherlands </p><p>New Caledonia </p><p>New Zealand </p><p>Nicaragua </p><p>Niger </p><p>Nigeria</p><p>Niue </p><p>Norfolk Island </p><p>Northern Mariana Islands</p><p>Norway </p></td><td><p>NA</p><p>NR</p><p>NP</p><p>NL</p><p>NC</p><p> NZ</p><p> NI</p><p>NE</p><p>NG</p><p>NU</p><p>NF</p><p>MP</p><p>NO</p></td></tr><tr><td>Oman</td><td>OM</td></tr><tr><td><p>Pakistan </p><p>Palau </p><p>Palestine, State of </p><p>Panama </p><p>Papua New Guinea </p><p>Paraguay</p><p>Peru </p><p>Philippines </p><p>Pitcairn </p><p>Poland </p><p>Portugal </p><p>Puerto Rico</p></td><td><p>PK</p><p>PW</p><p>PS</p><p>PA</p><p>PG</p><p>PY</p><p>PE</p><p>PH</p><p>PN</p><p>PL</p><p>PT</p><p>PR</p></td></tr><tr><td>Qatar </td><td>QA</td></tr><tr><td><p>Réunion </p><p>Romania </p><p>Russian Federation </p><p>Rwanda </p></td><td><p>RE</p><p>RO</p><p>RU</p><p>RW</p></td></tr><tr><td><p>Saint Barthélemy </p><p>Saint Helena, Ascension, and Tristan da Cunha</p><p>Saint Kitts and Nevis </p><p>Saint Lucia </p><p>Saint Martin (French part) </p><p>Saint Pierre and Miquelon </p><p>Saint Vincent and the Grenadines </p><p>Samoa</p><p>San Marino </p><p>Sao Tome and Principe </p><p>Saudi Arabia </p><p>Senegal </p><p>Serbia </p><p>Seychelles </p><p>Sierra Leone</p><p>Singapore </p><p>Sint Maarten (Dutch part) </p><p>Slovakia </p><p>Slovenia </p><p>Solomon Islands </p><p>Somalia </p><p>South Africa </p><p>South Georgia and the South Sandwich Islands </p><p>South Sudan </p><p>Spain</p><p>Sri Lanka</p><p>Sudan </p><p>Suriname </p><p>Svalbard and Jan Mayen</p><p>Swaziland </p><p>Sweden </p><p>Switzerland </p><p>Syrian Arab Republic </p></td><td><p>BL</p><p>SH</p><p>KN</p><p>LC</p><p>MF</p><p>PM</p><p>VC</p><p>WS</p><p>SM</p><p>ST</p><p>SA</p><p>SN</p><p>RS</p><p>SC</p><p>SL</p><p>SG</p><p>SX</p><p>SK</p><p>SI</p><p>SB</p><p>SO</p><p>ZA</p><p>GS</p><p>SS</p><p>ES</p><p>LK</p><p>SD</p><p>SR</p><p>SJ</p><p>SZ</p><p>SE</p><p>CH</p><p>SY</p></td></tr><tr><td><p>Taiwan, Province of China</p><p>Tajikistan</p><p>Tanzania, United Republic of </p><p>Thailand </p><p>Timor-Leste</p><p>Togo </p><p>Tokelau </p><p>Tonga</p><p>Trinidad and Tobago -</p><p>Tunisia </p><p>Turkey</p><p>Turkmenistan </p><p>Turks and Caicos Islands </p><p>Tuvalu</p></td><td><p>TW</p><p>TJ</p><p>TZ</p><p>TH</p><p>TL</p><p>TG</p><p>TK</p><p>TO</p><p>TT</p><p>TN</p><p>TR</p><p>TM</p><p>TC</p><p>TV</p></td></tr><tr><td><p>Uganda </p><p>Ukraine </p><p>United Arab Emirates </p><p>United Kingdom </p><p>United States </p><p>United States Minor Outlying Islands </p><p>Uruguay </p><p>Uzbekistan </p></td><td><p>UG</p><p>UA</p><p>AE</p><p>GB</p><p>US</p><p>UM</p><p>UY</p><p>UZ</p></td></tr><tr><td><p>Vanuatu </p><p>Venezuela, Bolivarian Republic of </p><p>Viet Nam</p><p>Virgin Islands, British </p><p>Virgin Islands, U.S.</p></td><td><p>VU</p><p>VE</p><p>VN</p><p>VG</p><p>VI</p></td></tr><tr><td><p>Wallis and Futuna </p><p>Western Sahar</p></td><td><p>WF</p><p>EH</p></td></tr><tr><td>Yemen </td><td>YE</td></tr><tr><td><p>Zambia </p><p>Zimbabwe</p></td><td><p>ZM</p><p>ZW</p></td></tr></tbody></table>


# Supported Currencies and Payment Gateways

This document outlines the currencies supported by Stripe, Razorpay, and PayPal across various countries. The information is categorized by country code and the respective currency.

##


# Stripe Supported Country with Currency

##

<table><thead><tr><th width="280">Country code to currency </th><th>Currency Codes</th></tr></thead><tbody><tr><td><p>AE </p><p>AF </p><p>AM </p><p>AN </p><p>AO </p><p>AR </p><p>AT </p><p>AU </p><p>AW </p><p>AZ</p></td><td><p>AED </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>ARS </p><p>EUR </p><p>AUD </p><p>AWG </p><p>USD</p></td></tr><tr><td><p>BA </p><p>BB </p><p>BD </p><p>BE </p><p>BG </p><p>BH </p><p>BI </p><p>BM </p><p>BN </p><p>BO </p><p>BR </p><p>BS </p><p>BT </p><p>BW </p><p>BY</p><p>BZ</p></td><td><p>EUR </p><p>BBD </p><p>BDT </p><p>EUR </p><p>EUR </p><p>USD </p><p>USD </p><p>BMD </p><p>BND </p><p>BOB </p><p>USD </p><p>BSD </p><p>USD </p><p>BWP </p><p>USD </p><p>BZD</p></td></tr><tr><td><p>CA </p><p>CD </p><p>CH </p><p>CL </p><p>CN </p><p>CO </p><p>CR </p><p>CV </p><p>CZ</p></td><td><p>CAD </p><p>USD </p><p>EUR </p><p>USD </p><p>CNY </p><p>COP </p><p>CRC </p><p>USD </p><p>CZK</p></td></tr><tr><td><p>DJ </p><p>DE </p><p>DK </p><p>DO </p><p>DZ </p><p>EG </p><p>ER </p><p>ET </p><p>EU </p><p>FJ </p><p>FR </p><p>FK</p></td><td><p>USD </p><p>EUR </p><p>DKK </p><p>DOP </p><p>DZD </p><p>EGP </p><p>USD </p><p>ETB </p><p>EUR </p><p>FJD </p><p>EUR </p><p>USD</p></td></tr><tr><td><p>GB </p><p>GE </p><p>GR </p><p>GG </p><p>GI </p><p>GM </p><p>GN </p><p>GT </p><p>GY </p><p>HK </p><p>HN </p><p>HT </p><p>HU</p></td><td><p>GBP </p><p>USD </p><p>EUR </p><p>USD </p><p>GIP </p><p>GMD </p><p>USD </p><p>GTQ </p><p>GYD</p><p>HKD </p><p>HNL </p><p>HTG </p><p>HUF</p></td></tr><tr><td><p>ID </p><p>IL </p><p>IE </p><p>IT </p><p>IM </p><p>IN </p><p>IQ </p><p>IR </p><p>IS </p><p>JE </p><p>JM </p><p>JO </p><p>JP</p></td><td><p>IDR </p><p>ILS </p><p>EUR </p><p>EUR </p><p>USD </p><p>INR </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>JMD </p><p>USD </p><p>USD</p></td></tr><tr><td><p>KE </p><p>KG </p><p>KH </p><p>KM </p><p>KP </p><p>KR </p><p>KW </p><p>KY </p><p>KZ </p><p>LA </p><p>LB </p><p>LK </p><p>LR </p><p>LS </p><p>LT </p><p>LU </p><p>LV </p><p>LY</p></td><td><p>KES </p><p>KGS </p><p>KHR </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>KYD </p><p>KZT </p><p>LAK </p><p>LBP </p><p>LKR </p><p>LRD </p><p>LSL </p><p>USD </p><p>EUR </p><p>USD </p><p>USD</p></td></tr><tr><td><p>MA </p><p>MC </p><p>MD </p><p>MG </p><p>MK </p><p>MM </p><p>MN </p><p>MO </p><p>MR </p><p>MU </p><p>MV </p><p>MW </p><p>MX </p><p>MY </p><p>MZ</p></td><td><p>MAD </p><p>EUR </p><p>MDL </p><p>USD </p><p>MKD </p><p>MMK </p><p>MNT </p><p>MOP </p><p>USD </p><p>MUR </p><p>MVR </p><p>MWK </p><p>MXN </p><p>MYR </p><p>USD</p></td></tr><tr><td><p>NA </p><p>NG </p><p>NI </p><p>NL </p><p>NO </p><p>NP </p><p>NZ </p><p>OM </p><p>PA </p><p>PE </p><p>PG </p><p>PH </p><p>PK </p><p>PL </p><p>Pt </p><p>PY</p></td><td><p>NAD </p><p>NGN </p><p>NIO </p><p>EUR </p><p>NOK </p><p>NPR </p><p>NZD </p><p>USD </p><p>USD </p><p>PEN </p><p>PGK </p><p>PHP </p><p>PKR </p><p>USD </p><p>EUR </p><p>USD</p></td></tr><tr><td><p>QA </p><p>RO </p><p>CS </p><p>RU </p><p>RW </p><p>ES </p><p>SA </p><p>SB </p><p>SC </p><p>SD </p><p>SE </p><p>SG </p><p>SH </p><p>SO </p><p>SR </p><p>ST </p><p>SY </p><p>SZ</p></td><td><p>QAR </p><p>EUR </p><p>USD </p><p>RUB </p><p>USD </p><p>EUR </p><p>SAR </p><p>USD </p><p>SCR </p><p>USD </p><p>SEK </p><p>SGD </p><p>USD </p><p>SOS </p><p>USD </p><p>USD </p><p>USD </p><p>SZL</p></td></tr><tr><td><p>TH </p><p>TJ </p><p>TM </p><p>TN </p><p>TO </p><p>TR </p><p>TT </p><p>TW </p><p>TZ </p><p>UA </p><p>UG </p><p>US </p><p>UY </p><p>UZ</p></td><td><p>THB </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>TTD </p><p>USD </p><p>TZS </p><p>USD </p><p>USD </p><p>USD </p><p>UYU </p><p>UZS</p></td></tr><tr><td><p>VE </p><p>VN </p><p>VU </p><p>WS </p><p>XA </p><p>XC </p><p>XD </p><p>XO </p><p>XP </p><p>YE </p></td><td><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>YER</p></td></tr><tr><td><p>ZA </p><p>ZM </p><p>ZW</p></td><td><p>ZAR </p><p>USD </p><p>USD</p></td></tr></tbody></table>


# Razorpay Supported Country with Currency

##

<table><thead><tr><th width="280">Country code to currency </th><th>Currency Codes</th></tr></thead><tbody><tr><td><p>AE </p><p>AF </p><p>AM </p><p>AN </p><p>AO </p><p>AR </p><p>AT </p><p>AU </p><p>AW </p><p>AZ</p></td><td><p>AED </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>ARS </p><p>EUR </p><p>AUD </p><p>AWG </p><p>USD</p></td></tr><tr><td><p>BA </p><p>BB </p><p>BD </p><p>BE </p><p>BG </p><p>BH </p><p>BI </p><p>BM </p><p>BN </p><p>BO </p><p>BR </p><p>BS </p><p>BT </p><p>BW </p><p>BY </p><p>BZ</p></td><td><p>EUR </p><p>BBD </p><p>BDT </p><p>EUR </p><p>EUR </p><p>USD </p><p>USD </p><p>BMD </p><p>BND </p><p>BOB </p><p>USD </p><p>BSD </p><p>USD </p><p>BWP </p><p>USD </p><p>BZD</p></td></tr><tr><td><p>CA </p><p>CD </p><p>CH </p><p>CL </p><p>CN </p><p>CO </p><p>CR </p><p>CU </p><p>CV </p><p>CZ</p></td><td><p>CAD </p><p>USD </p><p>EUR </p><p>USD </p><p>CNY </p><p>COP </p><p>CRC </p><p>CUP </p><p>USD </p><p>CZK</p></td></tr><tr><td><p>DJ </p><p>DE </p><p>DK </p><p>DO </p><p>DZ </p><p>EG </p><p>ER </p><p>ET </p><p>EU </p><p>FJ </p><p>FR </p><p>FK</p></td><td><p>USD </p><p>EUR </p><p>DKK </p><p>DOP </p><p>DZD </p><p>EGP </p><p>USD </p><p>ETB </p><p>EUR </p><p>FJD </p><p>EUR </p><p>USD</p></td></tr><tr><td><p>GB </p><p>GE </p><p>GR </p><p>GG </p><p>GH </p><p>GI </p><p>GM </p><p>GN </p><p>GT </p><p>GY</p></td><td><p>GBP </p><p>USD </p><p>EUR </p><p>USD </p><p>GHS </p><p>GIP </p><p>GMD </p><p>USD </p><p>GTQ </p><p>GYD</p></td></tr><tr><td><p>HK </p><p>HN </p><p>HR </p><p>HT </p><p>HU </p><p>ID </p><p>IL </p><p>IE </p><p>IT </p><p>IM </p><p>IN </p><p>IQ </p><p>IR </p><p>IS</p></td><td><p>HKD </p><p>HNL </p><p>HRK </p><p>HTG </p><p>HUF </p><p>IDR </p><p>ILS </p><p>EUR </p><p>EUR </p><p>USD </p><p>INR </p><p>USD </p><p>USD </p><p>USD</p></td></tr><tr><td><p>JE </p><p>JM </p><p>JO </p><p>JP </p><p>KE </p><p>KG </p><p>KH </p><p>KM </p><p>KP </p><p>KR </p><p>KW </p><p>KY </p><p>KZ</p></td><td><p>USD </p><p>JMD </p><p>USD </p><p>USD </p><p>KES </p><p>KGS </p><p>KHR </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>KYD </p><p>KZT</p></td></tr><tr><td><p>LA </p><p>LK </p><p>LR </p><p>LS </p><p>LT </p><p>LU </p><p>LV </p><p>LY </p><p>MA </p><p>MC </p><p>MD </p><p>MG </p><p>MK </p><p>MM </p><p>MN </p><p>MO </p><p>MR </p><p>MU </p><p>MV </p><p>MW </p><p>MX </p><p>MY</p><p>MZ</p></td><td><p>LAK </p><p>LKR </p><p>LRD </p><p>LSL </p><p>USD </p><p>EUR </p><p>USD </p><p>USD </p><p>MAD </p><p>EUR </p><p>MDL </p><p>USD </p><p>MKD </p><p>MMK </p><p>MNT </p><p>MOP </p><p>USD </p><p>MUR </p><p>MVR </p><p>MWK </p><p>MXN </p><p>MYR </p><p>USD</p></td></tr><tr><td><p>NA </p><p>NG </p><p>NI </p><p>NL </p><p>NO </p><p>NP </p><p>NZ </p><p>OM </p><p>PA </p><p>PE </p><p>PG </p><p>PH </p><p>PK </p><p>PL </p><p>Pt </p><p>PY</p></td><td><p>NAD </p><p>NGN </p><p>NIO </p><p>EUR </p><p>NOK </p><p>NPR </p><p>NZD </p><p>USD </p><p>USD </p><p>PEN </p><p>PGK </p><p>PHP </p><p>PKR </p><p>USD </p><p>EUR </p><p>USD</p></td></tr><tr><td><p>QA </p><p>RO </p><p>CS </p><p>RU </p><p>RW </p><p>ES </p><p>SA </p><p>SB </p><p>SC </p><p>SD </p><p>SE </p><p>SG </p><p>SH </p><p>SL </p><p>SO </p><p>SR </p><p>ST </p><p>SV </p><p>SY </p><p>SZ</p></td><td><p>QAR </p><p>EUR </p><p>USD </p><p>RUB </p><p>USD</p><p>EUR </p><p>SAR </p><p>USD </p><p>SCR </p><p>USD </p><p>SEK </p><p>SGD </p><p>USD </p><p>SLL </p><p>SOS </p><p>USD </p><p>USD </p><p>SVC </p><p>USD </p><p>SZL</p></td></tr><tr><td><p>TH </p><p>TJ </p><p>TM </p><p>TN </p><p>TO </p><p>TR </p><p>TT </p><p>TW </p><p>TZ </p><p>UA </p><p>UG </p><p>US </p><p>UY</p><p>UZ</p></td><td><p>THB </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>TTD </p><p>USD </p><p>TZS </p><p>USD </p><p>USD </p><p>USD </p><p>UYU </p><p>UZS</p></td></tr><tr><td><p>VE </p><p>VN </p><p>VU </p><p>WS </p><p>XA </p><p>XC </p><p>XD </p><p>XO </p><p>XP </p><p>YE </p></td><td><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>YER</p></td></tr><tr><td><p>ZA </p><p>ZM </p><p>ZW</p></td><td><p>ZAR </p><p>USD </p><p>USD</p></td></tr></tbody></table>


# Paypal Supported Country with Currency

##

<table><thead><tr><th width="280">Country code to currency </th><th>Currency Codes</th></tr></thead><tbody><tr><td><p>AF </p><p>AM </p><p>AN </p><p>AO </p><p>AT </p><p>AU </p><p>AZ</p></td><td><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>EUR </p><p>AUD </p><p>USD</p></td></tr><tr><td><p>BA </p><p>BE </p><p>BG </p><p>BH </p><p>BI </p><p>BR </p><p>BT </p><p>BY</p></td><td><p>EUR </p><p>EUR </p><p>EUR </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD</p></td></tr><tr><td><p>CA </p><p>CD </p><p>CH </p><p>CL </p><p>CN </p><p>CV </p><p>CZ </p><p>DJ </p><p>DE </p><p>DK</p></td><td><p>CAD </p><p>USD </p><p>EUR </p><p>USD </p><p>CNY </p><p>USD </p><p>CZK </p><p>USD </p><p>EUR </p><p>DKK</p></td></tr><tr><td><p>ER </p><p>EU </p><p>FR </p><p>FK </p><p>GB </p><p>GE</p><p>GR</p><p>GG </p><p>GN </p><p>HK </p><p>HU</p></td><td><p>USD </p><p>EUR </p><p>EUR </p><p>USD </p><p>GBP </p><p>USD </p><p>EUR </p><p>USD </p><p>USD </p><p>HKD </p><p>HUF</p></td></tr><tr><td><p>IL </p><p>IE </p><p>IT </p><p>IM </p><p>IQ </p><p>IR </p><p>IS </p><p>JE</p><p>JO </p><p>JP </p><p>KM </p><p>KP </p><p>KR </p><p>KW</p></td><td><p>ILS </p><p>EUR </p><p>EUR </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD</p></td></tr><tr><td><p>LT </p><p>LU </p><p>LV </p><p>LY </p><p>MC </p><p>MG </p><p>MR </p><p>MX </p><p>MY </p><p>MZ </p><p>NL </p><p>NO </p><p>NZ </p><p>OM</p></td><td><p>USD </p><p>EUR </p><p>USD </p><p>USD </p><p>EUR </p><p>USD </p><p>USD </p><p>MXN </p><p>MYR </p><p>USD </p><p>EUR </p><p>NOK </p><p>NZD </p><p>USD</p></td></tr><tr><td><p>PA </p><p>PH </p><p>PL </p><p>Pt </p><p>PY </p><p>RO </p><p>CS </p><p>RW </p><p>ES</p></td><td><p>USD </p><p>PHP </p><p>USD </p><p>EUR </p><p>USD </p><p>EUR </p><p>USD </p><p>USD </p><p>EUR</p></td></tr><tr><td><p>SB </p><p>SD </p><p>SE </p><p>SG </p><p>SH </p><p>SR </p><p>ST </p><p>SY </p><p>TH </p><p>TJ </p><p>TM </p><p>TN </p><p>TO </p><p>TR </p><p>TW</p></td><td><p>USD </p><p>USD </p><p>SEK </p><p>SGD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>THB </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD</p></td></tr><tr><td><p>UA </p><p>UG </p><p>US </p><p>VE </p><p>VN </p><p>VU </p><p>WS</p></td><td><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD</p></td></tr><tr><td><p>XA </p><p>XC </p><p>XD </p><p>XO </p><p>XP </p><p>ZM </p><p>ZW</p></td><td><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD </p><p>USD</p></td></tr></tbody></table>


# Errors

<table><thead><tr><th width="264.5">ERROR CODE</th><th>MEANING</th></tr></thead><tbody><tr><td>400</td><td>Bad Request -- Your request is invalid.</td></tr><tr><td>401</td><td>Unauthorized -- Invalid API Key &#x26; API Secret.</td></tr><tr><td>403</td><td>Forbidden -- The resource requested is hidden for administrators only.</td></tr><tr><td>404</td><td>Not Found -- The resource requested could not be found.</td></tr><tr><td>405</td><td>Method Not Allowed -- You tried to access a resource with an invalid method.</td></tr><tr><td>406</td><td>Not Acceptable -- You requested a format that isn't JSON.</td></tr><tr><td>410</td><td>Gone -- The resource has been removed from our servers.</td></tr><tr><td>418</td><td>I'm a teapot.</td></tr><tr><td>429</td><td>Too Many Requests -- You're requesting too many resources! Slow down!</td></tr><tr><td>500</td><td>Internal Server Error -- We had a problem with our server. Try again later.</td></tr><tr><td>503</td><td>Service Unavailable -- We're temporarily offline for maintenance. Please try again later.</td></tr></tbody></table>


# Loyalty System


# Web SDK

To inspire and enhance users' in-app behavior, Conscent.ai enables you to build gamified challenges. Any event may be made more engaging by using game elements like cash, your own branded virtual coins, voucher codes for your brand, or any other 3rd party voucher code incentives.

With its Plug & Play SDK, Conscent.ai incorporates these game elements into your program. From its Web Dashboard, it enables you to administer these gamified challenges. These challenges are known as Campaigns.

Users can be rewarded for accomplishing specific tasks in each campaign, such as opening a new account, completing KYC, making purchases that exceed a specified threshold, or checking in every day. Conscent.ai offers a reward to a user as a Scratch Card once they successfully finish a job. Cash, virtual coins, or voucher codes are all possible prize types for this scratch card.

Events are the core of the rewards program. The Events that the user receives as a result of their activities are tracked by Conscent.ai Rewards System, which also decides if they are eligible for rewards. When a user completes the intended task or transaction, your backend notifies Conscent.ai of the event by making an API request. The Rewards System searches for Campaigns linked to this Event, verifies eligibility, and then gives the user their prize.

**Developer's Guide**

If you are a developer, you can get started by setting up the SDK in your application.

**Web Plugin**

`Version:- 1.0.1`

<details>

<summary><mark style="color:orange;"><strong>How to add Web Plugin in HTML Web Application</strong></mark></summary>

**Step 1:  Include Bluepine’s SDK in your Web Application**

```javascript
 <script type="text/javascript" src="https://unpkg.com/bluepine-web-sdk/dist/BluepineSDK.min.js" defer></script>
```

**Step 2: Start Bluepine in your Web Application for Non-logged in users**

```javascript
<script type="text/javascript">
  (function () {
    var data = {
      partner_id: "<Take this from conscent.ai dashboard>"
    };
    window.onload = function(){
    bluepine.initSDK(data);
  }
  })();
</script>
```

**Step 3: Initialise the SDK for a Logged-in/Signed Up User**

```javascript
<script type="text/javascript">
  (function () {
    var data = {
      partner_id: "<Take this from dashboard>",
      user_id: "<unique user id>"
    };

    window.onload = function(){
        bluepine.initSDK(data);
    }
  })();
</script>
```

</details>

<details>

<summary><mark style="color:orange;">How to add Web Plugin in React Web Application</mark></summary>

**Step 1: Include Bluepine’s SDK in your Web Application**

* Install package

```javascript
npm i bluepine-sdk
```

* import package

```javascript
import bluepine from 'bluepine-web-sdk';
```

**Step 2: Start Bluepine in your Web Application for Non-logged in users**

```javascript
    var data = {
      partner_id: "<Take this from bluepine dashboard>"
    };

    bluepine.initSDK(data);a
```

**Step 3: Initialise the SDK for a Logged-in/Signed Up User**

```javascript
    var data = {
      partner_id: "<Take this from dashboard>",
      user_id: "<unique user id>"
    };

    bluepine.initSDK(data);

```

</details>

**Send User Events**

Send User Events using Server-to-Server setup using User Events API.

[https://app.gitbook.com/o/1sDsqE1CXFmByJ8w0zlZ/s/coDfVWiJBvgTq8DbifIH/\~/changes/103/loyalty-system/api-from-server](/loyalty-system/api-from-server)

**Function to show Bluepine Club Button**

```javascript
bluepine.showBluepineButton();
```

**Function to Hide Bluepine Club Button**

```javascript
bluepine.hideBluepineButton();
```

**Change a position of button**

By default the position of the button is to the left but if you want to change the position to the right then set the position of the button to the right before calling `bluepineSDK.initSDK();`

```javascript
bluepine.btnPosition="right";
```


# iOS SDK

Setting up the Conscent.ai SDK (Loyalty Platform) in your Xcode project

### **Initialize SDK**

The following guide provides steps to initialize the Conscent.ai SDK for your Xcode project. Please follow all the steps below carefully.

> Minimum iOS Version required is: 14

### Add Dependencies

Within the target block of your project's Podfile, define the Conscent.ai dependency.

```java
 target 'yourxcodeproject' do
         pod 'BluePine', '0.1.1'
end

```

Then, run the following command from the Terminal from the root of your Xcode project's directory to install the dependency.

```
pod install
```

If pod install fails for some reason, run pod update and pod repo update and try again.

### **Pair SDK with Dashboard**

Register Package Name

Open your Conscent.ai Dashboard and go to Settings > Basic Details and register a Package Name.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FCUSEOpp0hmgAsmxJ8OL8%2FScreenshot%202023-06-29%20at%202.22.52%20PM.png?alt=media&amp;token=906c03c1-e562-4351-a325-cd78f7e64596" alt=""><figcaption></figcaption></figure>

### Set Package Name & Initialize SDK

Initialize the SDK anywhere in your project.

```java
import BluePine
   @main
   class AppDelegate: UIResponder, UIApplicationDelegate {
         func application(_ application: UIApplication,
   didFinishLaunchingWithOptions launchOptions:
   [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
...
                BluePine.setPartnerIdAndUserId(partnerId: "<partner_id>",
   userId: "<user_id>")
           BluePine.startBluePine()
   ...
} ... }
```

> 1. partner\_id details is available in settings page under basic details.
> 2. user\_id can be any string that will be shown in reports. This must be unique and cannot be changed for any User later on.


# Android SDK

Setting up the Conscent.ai SDK (Loyalty Platform) in your Android app

### Initialize SDK

The following guide provides steps to initialize the Conscent.ai SDK for your Android application. Please follow all the steps below carefully.

> minimum sdk required is 26. Please change it in app/build.gradle

### Add Dependencies

Add Auth Token

To access Bluepine’s private JitPack library, add this line in your project's gradle.properties file (your\_project/gradle.properties):

```java
authToken=jp_lumadc0egqfu7bvmh1g7pe9t13
```

**Add JitPack Repository**

In your project-level build.gradle file (your\_project/build.gradle), add the

maven repository inside the <mark style="color:green;">allprojects</mark> closure:

```java
buildscript {
     ...
   }
   allprojects {
      repositories {
          ...
          maven {
              url "http://jitpack.io"
              credentials { username authToken }
} }
}
```

**Gradle 7.0+**

If the allprojects closure does not exist, in your project's settings.gradle file (your\_project/settings.gradle), add the maven repository:

```java
  dependencyResolutionManagement {
       repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
       repositories {
... maven {
               url "http://jitpack.io"
               credentials { username authToken }
           }
} }
```

**Add the Conscent.ai SDK dependency**

```java
implementation 'club.conscent:loyalty_native_android:1.2.7'
```

Sync your project with Gradle files by clicking Sync Now.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FWgBghYzHjR0aFRcMjfGu%2FScreenshot%202023-06-29%20at%201.39.42%20PM.png?alt=media&amp;token=9abbaf90-f94e-4573-92ab-95654f55c854" alt="" width="375"><figcaption><p>Sync should succeed, at this point</p></figcaption></figure>

**Pair SDK with Dashboard**

Register Package Name

Open your Conscent .aiDashboard and go to Settings > Basic Details and register a Package Name.

<figure><img src="https://380225236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcoDfVWiJBvgTq8DbifIH%2Fuploads%2FTcZyFvpQHRGduPFSVLAe%2FScreenshot%202023-06-29%20at%201.39.07%20PM.png?alt=media&amp;token=4fd21aef-dac8-48db-80f3-66099bab8580" alt=""><figcaption></figcaption></figure>

**Set Package Name**

Bluepine.setPackageName("\<package\_name\_same\_as\_registered\_in\_cons cent\_dashboard>");

**Initialize SDK**

The final step of initialization is to call the setPartnerIdAndUserId method. Initialise with a Partner ID

```java
BluePine.setPartnerIdAndUserId(“partnerId”, “UserID”)
```

**Initialize the SDK in your app's Application class or main entry point of the app. For integration purposes:**

* *If you are under activity*

```java
  import com.example.bluepine.module.BluePine
  class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      BluePine.stateBluePine(this.applicationContext)
} }
```

* *If you are in a composable*

```java
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier)
{
  val context = LocalContext.current
  Text(
    text = “Open BluePine”,
    modifier = Modifier.clickable {
      BluePine.stateBluePine(context)
    },
) }
```


# Flutter SDK

This project is a starting point for a Flutter [plug-in package](https://flutter.dev/developing-packages/), a specialized package that includes platform-specific implementation code for Android and/or iOS.

For help getting started with Flutter development, view the [online documentation](https://flutter.dev/docs), which offers tutorials, samples, guidance on mobile development, and a full API reference.

```dart
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:purplepro/purplepro.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _purpleproPlugin = Purplepro();

  @override
  void initState() {
    super.initState();
    initPurpleProPlugin();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPurpleProPlugin() async {
    _purpleproPlugin.setPartnerIdAndUserId(partnerId: "77010207011", userId: "5842918d-7d0f-4091-ab8b-4a6abfb5bf22");
  }

  Future<void> startPurplepro() async {
    _purpleproPlugin.startBluePine(darkMode: false);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  startPurplepro();
                },
                child: const Text('Enabled'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
```

**Installation Steps:**

### Use this package as a library

#### Depend on it

Run this command:

With Flutter:

```shell
 $ flutter pub add purplepro
```

This will add a line like this to your package's pubspec.yaml (and run an implicit `flutter pub get`):

```dart
dependencies:
purplepro: ^0.0.1
```

Alternatively, your editor might support `flutter pub get`. Check the docs for your editor to learn more.

#### Import it

Now in your Dart code, you can use:

```dart
import 'package:purplepro/purplepro.dart';
```

[API reference](https://pub.dev/documentation/purplepro/latest/)

[flutter](https://api.flutter.dev/), [plugin\_platform\_interface](https://pub.dev/packages/plugin_platform_interface)

[<mark style="color:blue;">Packages that depend on c</mark>](https://pub.dev/packages?q=dependency%3Apurplepro)<mark style="color:blue;">onscent.ai</mark>




---

[Next Page](/llms-full.txt/1)

