Javascript SDK

Pelcro JavaScript SDK empowers businesses to provide users a seamless experience in a matter of minutes. Check out the examples below for more information.

Install

To install the JS-SDK, copy and paste the code below before the tag on every page of your site. You can find a script on the integration page from the settings of the platform.

<script>var Pelcro = window.Pelcro || (window.Pelcro = {}); Pelcro.siteid = "ID";</script>
<script async src="//js.pelcro.com/sdk/main.min.js" type="text/javascript"></script>

Configure

We offer enterprise clients access to a staging environment where they can run tests. To configure a testing environment, set the options below in the SDK. Contact our sales team to learn more about a staging environment.

General

Always make sure to instantiate an empty object first.

<script>Pelcro.environment = {};</script>

This will override the domain to use the staging environment.

<script>Pelcro.environment.domain = "https://staging.pelcro.com";</script>

To trigger your own user interface layer, you can set it using the env as shown below. Available to specific plans only.

<script>Pelcro.environment.ui = "ui-react.bunlde.js";</script>

To use fake CC transactions, enter your Stripe test public key as shown below.

<script>Pelcro.environment.stripe = "pk_test_000000000000000000000000";</script>

Example of all steps above.

var Pelcro = window.Pelcro || (window.Pelcro = {});
Pelcro.siteid = "0";
Pelcro.environment = {};
Pelcro.environment.stripe = "pk_test_000000000000000000000000";
Pelcro.environment.domain = "https://staging.pelcro.com";
Pelcro.environment.ui = "ui-react.bunlde.js";

E-commerce

In order to enable the E-commerce feature, you have to do two steps:

  • Configure your E-commerce products on the platform.
  • Enable the E-commerce feature in site settings

SDK-only

If you wish to leverage the SDK only without a user interface, just enter "-" in the environment UI variable.

Core module

All examples below are JS examples of the Pelcro object that is a global variable in the window object. The default Pelcro flow and UI uses all the SDK functions below automatically without any additional coding requirements by the publisher. The functions below can allow you create your own UI and flow layer by using the SDK functions below.

Authentication
Pelcro uses JWT to authenticate users and identify them. A JSON Web Token (JWT) is a JSON object that is defined in RFC 7519 as a safe way to represent a set of information between two parties. The JWT token is reference as authToken in the documentation below.

Callbacks
All call backs return a response or error object in the following order function(err, resp). Error messages returned by the API are accessible as following: err.response.data.error.message

Errors
All errors are returned back from the API. Requests will be validated by the API using server side validations. Error messages returned by the API are accessible as following: err.response.data.error.message. API responses for errors will be either 4xx or 5xx depending on the severity of the error. Validation errors will be 4xx while server errors will be 5xx.

Site


Get the current site data which contains all of your product configurations. This variable is available upon the PelcroSiteLoaded event which is triggered once the SDK has loaded the site configuration from the API call.

Pelcro.site.read()

Fetch the latest site data from Pelcro

Pelcro.site.getById(callback)

User

Create a user with his email and password

Pelcro.user.register({first_name: "", last_name: "", email: "", password: "", phone:"", display_name:"", salutation:"", title:"", metadata: ""}, callback)

Verify user credentials with the login function. The response will also contain user addresses and invoices

Pelcro.user.login({email: "", password: ""}, callback)

Authenticate a user with an IDP, currently supporting google and facebook.

Pelcro.user.idpLogin({
  idp_name: "google", 
  idp_token: "",
  email: "", 
  first_name: "",
  last_name: "",
  phone: "",
  display_name: "",
  metadata: "",
  salutation: ""
}, callback)

Authenticate a user with an auth token, and fetch the user resource.

Pelcro.user.authenticate({ auth_token: ""}, callback)

Refresh the auth token, and fetch the user resource.

Pelcro.user.refresh({ auth_token: ""}, callback)

Update user information such as name and phone number

Pelcro.user.update({first_name: "", last_name: "", phone: "", metadata: "", display_name: "", salutation: "", title: ""}, callback)

Logout current user by removing any authentication cookies.

Pelcro.user.logout()

Check if the user is authenticated

Pelcro.user.isAuthenticated();

To get the user object and all its associated properties, you can read the user object as follows. This will only work for authenticated users.

Pelcro.user.read()

Checks if the user has a specific entitlement and returns a boolean value.

Pelcro.user.isEntitledTo("test_entitlements")

Add values to user's metadata.

Pelcro.user.saveToMetaData({
  key: "",
  value: "",
  auth_token: "",
}, callback)

Upload a new user profile picture. picture format must be PNG or JPG, and must be a square, with a minimum dimension of 150px, and a maximum of 500px.

Pelcro.user.uploadProfilePicture({image: myImageBlob, auth_token: ""}, callback)

Remove the user's current profile picture.

Pelcro.user.removeProfilePicture({auth_token: ""}, callback)

Payment source

Add the user payment source.

Pelcro.source.create({auth_token: "", token: "stripe_token"}, callback)

Update the user payment source.

Pelcro.source.update({auth_token: "", source_id: "", cc_exp: "12/25"}, callback)

Social Logins

Facebook

To get the user data using a Facebook login button, connect an HTML button to the SDK function below. You can pass the required scopes to the SDK function based on your requirements.

window.Pelcro.social.getUserDataFromFacebook(
      {
        appId:
          window.Pelcro.site.read() &&
          window.Pelcro.site.read().facebook_app_id,
        scope: "email"
      },
      (err, res) => console.log(err, res)
    );

Google

To get the user data using a Google login button, connect an HTML button to the SDK function below. You can pass the required scopes to the SDK function based on your requirements.

window.Pelcro.social.getUserDataFromGoogle(
      {
        appId:
          window.Pelcro.site.read() &&
          window.Pelcro.site.read().google_app_id,
        scope: "email"
      },
      (err, res) => console.log(err, res)
    );

Password

To send a password reset email to the user, simply call this function.

Pelcro.password.forgot({email: ""}, callback)

To reset the user's password, you will need the token from the URL that is sent to the user by email (token)

Pelcro.password.reset({email: "", password: "", password_confirmation: "", token: ""}, callback)

To update the user's password, you will need the old password, new password and confirmation of the new password.

Pelcro.password.update({old_password: "", new_password: "", confirm_new_password: ""}, callback)

Subscription

Create a subscription for a user.
A payment gateway must be set whether its (stripe|braintree), gateway token is required to create a subscription, you can use Stripe|BrainTree JS-SDK to tokenize a credit card. Learn more Stripe | BrainTree
.

Pelcro.subscription.create({payment_gateway:"stripe", gateway_token: "", pay_via_send_invoice: false, auth_token: "", plan_id: "", coupon_code: "", gift_recipient_email: "", gift_recipient_first_name: "", gift_recipient_last_name: "", gift_recipient_full_name: "", gift_start_date: "", gift_message: "",  quantity: "", address_id: ""
, source_id: ""}, callback)

Cancel a subscription for a user

Pelcro.subscription.cancel({auth_token: "", subscription_id: ""}, callback)

Reactivate a subscription for a user

Pelcro.subscription.reactivate({auth_token: "", subscription_id: ""}, callback)

Renew a subscription for a user

Pelcro.subscription.renew({
  payment_gateway: "stripe",
  gateway_token: "",
  auth_token: "", 
  plan_id: "",
  subscription_id: "",
  coupon_code: "",
  address_id: "", 
  source_id: ""
}, callback)

Redeem a gifted subscription
(provide the optional subscription_id to add the redeemed subscription as a new phase to the existing subscription)

Pelcro.subscription.redeemGift({
  auth_token: "", 
  gift_code: "",
  address_id: "",
  subscription_id: "",
}, callback)

Renew a gifted subscription, as the donor.

Pelcro.subscription.renewGift({
  auth_token: "", 
    payment_gateway: "stripe",
  gateway_token: "",
  plan_id: "",
  subscription_id: "",
  coupon_code: "",
  address_id: "",
  quantity: "", 
  source_id: ""
}, callback)

List user's subscriptions

Pelcro.subscription.list()

Check if the user is subscribed to this site

Pelcro.subscription.isSubscribedToSite()

Check if the user is subscribed to a specific plan

Pelcro.subscription.isSubscribedToPlan({id: "plan_id"})

Invoices

Lists user's invoices

Pelcro.invoice.list()

Newsletter

Create a newsletter

Pelcro.newsletter.create({email: "", source: "", lists: "", consent_url: "", consent_text: "", consent_type: ""}, callback)

Get a newsletter by email

Pelcro.newsletter.getByEmail(email, callback)

Update a newsletter

Pelcro.newsletter.update({email: "", source: "", lists: "", consent_url: "", consent_text: "", consent_type: ""}, callback)

Check if the user is subscribed to the newsletter

Pelcro.newsletter.isSubscribedToNewsletter()

Product

List all available products, filtered according to user's currency & location.

Pelcro.product.list()

List all products targeting the current user

Pelcro.product.listByTarget()

Get a specific product.

Pelcro.product.getById(123)

Plan

Get a specific plan.

Pelcro.plan.getById(123)

Get an array of plans associated with the user's IP address

Pelcro.plan.getByIP(callback)

Fetch a specific plan from pelcro, including offline plans.

Pelcro.plan.getPlan({plan_id: 123}, callback)

Order

Calculates order's details, taxes & discount after coupon

Pelcro.order.create({
  auth_token: "", 
  plan_id: "",
  address_id: "",
  coupon_code: "",
}, callback)

Address

Create an address for an authenticated user

Pelcro.address.create({auth_token: "", type: "" (shipping or billing), first_name: "", last_name: "", line1: "", city: "", state: "", country: "", postal_code: ""}, callback)

Update an address for an authenticated user

Pelcro.address.update({auth_token: "", address_id:"", type: "" (shipping or billing), first_name: "", last_name: "", line1: "", city: "", state: "", country: "", postal_code: ""}, callback)

Paywall

Number of free visits left

Pelcro.paywall.freeVisitsLeft()

Should the newsletter paywall be displayed based on site configurations?

Pelcro.paywall.displayNewsletterPaywall()

Should the meter paywall be displayed based on site configurations?

Pelcro.paywall.displayMeterPaywall()

Should the paywall (block content) be displayed based on site configurations? (returns a boolean)

Pelcro.paywall.displayPaywall()

Get the paywall product targeting the user based on site configuration

Pelcro.paywall.getProduct()

Get the current active paywall object

Pelcro.paywall.read()

This function checks if the user is authorized to view this article based on the paywall rules set in the product configuration. The function returns true if the current article the user is browsing is restricted as he is not subscribed to the product associated with the paywall configuration.

Pelcro.paywall.isArticleRestricted()

E-commerce

In order to enable the E-commerce feature, you have to do two steps:

  • Configure your E-commerce products on the CRM.
  • Enable the E-commerce feature in site settings

Fetch E-commerce products from our backend
(automatically called if E-commerce feature is enabled in site settings).

window.Pelcro.ecommerce.products.list(callback);

Read the list of your E-commerce products

Calling this function provides you with a list of all the E-commerce products that you've configured on the CRM.

window.Pelcro.ecommerce.products.read();

Get a specific e-commerce product by its id.

Pelcro.ecommerce.products.getByProductId(123)

Get a specific e-commerce product's SKU by its SKU id.

Pelcro.ecommerce.products.getBySkuId(321)

Create an order

This SDK function allows you to checkout, or create an E-commerce order

window.Pelcro.ecommerce.order.create(
      {
        items: [
                {
                    "sku_id": 34,
                    "quantity": 1
                }
                ],
                payment_gateway: "stripe",
            gateway_token: "",
        source_id: "",
        address_id: 123
      },
      (err, res) => {
        console.log(err, res);
      }
    );

Insight module

Analytics

By default, page view events are tracked via Pelcro’s SDK. There is no need to trigger a custom event for every page view. Any interaction with our modals, meter or any view that Pelcro displays (if enabled) are automatically tracked and reported to your dashboard. If you are not using our default flows, then you might want to continue reading to learn how you can trigger custom events and properties.

Events are captured programmatically using code. In this example, an event named “Button clicked” is triggered. You should plan out and prioritize all the events that are relevant and important to your business and make sure they are all tracked. You should always have two goals in mind, what do I need to track and what data do I need for machine learning.

Pelcro.insight.track("Button clicked");

In the example below, we are adding two custom properties to the event in the previous example. By default, we track the following properties to every event that is triggered, so there is no need to do that again.

Pelcro.insight.track("Button clicked", {
    "name": Facebook like,
    "color": "Blue"
});

Default properties: This list is not exhaustive. We frequently add to this list any property we deem useful to our clients. You can view the up to date list in the segmentation report on your dashboard.

  • Event/action type
  • Country
  • Region
  • Scroll percentage
  • Time spent
  • UTM tags (source, medium, campaign, content, term)
  • OGP tags (article:tag, article:section, etc) - learn more here
  • Ad blocking status
  • Device
  • Referral source
  • Frequency (frequency of visitor on the site)
  • Device fingerprint
  • Local time
  • Device
  • Browser
  • Referral domain

Machine Learning Personalization

Plan recommendations

Plan recommendations per user powered by a neural network multi-class categorical probabilistic regression machine learning algorithm. Get plan recommendations for any specific user as shown below.

Pelcro.insight.getPlansRecommendations(
  {
    user_id: ""
  },
  callback
);

Subscription predictions

Subscription prediction API allows you to get the subscription predictions of non-paying customers powered by machine learning ensemble algorithms. Get the subscription prediction of a non-paying customer as shown below.

Pelcro.insight.getSubscriptionPrediction(
  {
    user_id: ""
  },
  callback
);

Churn prediction

Churn prediction API allows you to get the churn prediction of a paying customer powered by machine learning decision tree algorithms. Get the churn prediction of paying customers as shown below.

Pelcro.insight.getChurnPrediction(
  {
    user_id: ""
  },
  callback
);

Content recommendations

Content recommendation API powered by a hybrid recommendation system. Get all the content recommendations for a specific user as shown below.

Pelcro.insight.getContentRecommendations(
 {
   user_id: "",
 },
 callback
)

Get the filtered and boosted by section content recommendations.

Pelcro.insight.getContentRecommendations(
 {
   user_id: "",
   filter: ["filter", "tags"],
   boost: ["tags", "to", "boost"],
 },
 callback
)

Get the filtered, boosted by section, and boosted by paywall content recommendations.

Pelcro.insight.getContentRecommendations(
 {
   user_id: "",
   filter: ["filter", "tags"],
   boost: ["tags", "to", "boost"],
   boost_paywalled: true
 },
 callback
)

Helper methods

we expose some useful helper methods, for generic usecases.

getURLParameter

Returns a specific URL parameter.

const product_id = Pelcro.helpers.getURLParameter("product_id");

loadSDK

Loads a specified script into the document and gives it a specified ID.

Pelcro.helpers.loadSDK(
  "https://js.stripe.com/v3.js",
  "pelcro-sdk-stripe-id"
);

loadCSS

Same as loadSDK but for CSS files.

Pelcro.helpers.loadCSS(
  "https://js.stripe.com/v3/integrations/812.css",
  "pelcro-css"
);

Events

Listen to triggered events from the SDK and add your own reactions. No matter what you want to do, you can use our SDK to listen to events that are triggered. You can use these events to customize reactions for different events, integrate them with an analytics provider or customize the user experience based on them. The possibilities are endless.

  • PelcroSiteLoaded: This occurs when the site configuration has been loaded in the JS-SDK and hence window.Pelcro.site.read(); is now available.

  • PelcroUserRegister: This occurs when a user registers using the Pelcro JS-SDK.

  • PelcroUserLogin: This occurs when a user logs in using the Pelcro JS-SDK.

  • PelcroUserLogout: This occurs when a user logs out using the Pelcro JS-SDK.

  • PelcroSubscriptionCreate: This occurs when a subscription is created using the Pelcro JS-SDK.

  • PelcroSubscriptionCancel: This occurs when a subscription is canceled using the Pelcro JS-SDK.

  • PelcroUserLoaded: This occurs when the user object is updated via the Pelcro JS-SDK using the most up-to-date data from the API.

  • PelcroUserUpdated: This occurs when the user object is updated via the Pelcro JS-SDK.

  • PelcroAddressCreated: This occurs when the user's address object is created via the Pelcro JS-SDK.

  • PelcroAddressUpdated: This occurs when the user's address object is updated via the Pelcro JS-SDK.

  • PelcroSourceCreated: This occurs when the user's payment source object is created via the Pelcro JS-SDK.

  • PelcroPasswordForgot: This occurs when the password forgot is requested via the Pelcro JS-SDK.

  • PelcroPasswordReset: This occurs when the password gets reset via the Pelcro JS-SDK.

  • PelcroEcommerceProductsLoaded: This occurs when the e-commerce products are loaded. from the backend via the Pelcro JS-SDK using the most up-to-date data from the API.

  • PelcroOrderCreate: This occurs when a successful e-commerce order is created by a user, includes the order object in the event detail.

  • PelcroPaywallMatch: This occurs when it's possible to display the meter-paywall. It's calculated in the JS-SDK based on the free articles limit specified for the website, and the users' visits to that particular website. It returns an object that contains this data: count_of_articles_read, count_of_articles_left and count_of_articles_limit.

<script>
  
    document.addEventListener("PelcroSiteLoaded", function (e) {
        console.log("PelcroSiteLoaded");
    });
  
    document.addEventListener("PelcroUserRegister", function (e) {
        console.log("PelcroUserRegister");
    });

    document.addEventListener("PelcroUserLogin", function (e) {
        console.log("PelcroUserLogin");
    });

    document.addEventListener("PelcroUserLogout", function (e) {
        console.log("PelcroUserLogout");
    });

    document.addEventListener("PelcroSubscriptionCreate", function (e) {
        console.log("PelcroSubscriptionCreate");
    });

    document.addEventListener("PelcroUserLoaded", function (e) {
        console.log("PelcroUserLoaded");
    });
  
    document.addEventListener("PelcroEcommerceProductsLoaded", function (e) {
        console.log("PelcroEcommerceProductsLoaded");
    });
  
    document.addEventListener("PelcroOrderCreate", function (e) {
        console.log("PelcroOrderCreate");
    });
  
        document.addEventListener("PelcroPaywallMatch", function (e) {
        console.log("PelcroPaywallMatch", e?.detail);
    });
</script>
<script>
  document.addEventListener("PelcroUserLoaded", function (e) {
      // You can access all the data available on the user as shown below
      console.log(e.detail);
  });
</script>

Integrations

Pelcro offers multiple integrations. Some of which are abstracted on the JS-SDK to make it easier to use.

Disqus

The Disqus integration provides you with an out of the box SSO integration.

  • You can only make this call if the user is authenticated.
  • You will receive a data object containing the auth key and the public key
window.Pelcro.integrations.disqus.getToken(function(resp){});

Did this page help you?