Javascript SDK

Pelcro JavaScript SDK empowers businesses to provide users with a seamless experience in a matter of minutes.

Setup

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

Example Setup

<script>
  window.Pelcro = {};
  window.Pelcro.siteid = "8989";
  window.Pelcro.environment = {
    domain: "https://staging.pelcro.com",
    ui: "https://js.pelcro.com/ui/plugin/membership-staging/v1/main.min.js",
    stripe: "pk_test_aThAAdvPHgIdAziZweywBWNk"
  };
</script>
<script async src="https://js.pelcro.com/sdk/main.min.js" type="text/javascript"></script>

Reference

Parameter

Description

siteid

Your Pelcro site id.

domain

The base domain for all the requests going to Pelcro.
It can be either https://staging.pelcro.com for the staging environment or https://www.pelcro.com for the production environment.

ui

The UI bundle link.
The example uses the latest version of our staging default UI https://js.pelcro.com/ui/plugin/membership-staging/v1/main.min.js
This is the production version https://js.pelcro.com/ui/plugin/membership/v1/main.min.js
This parameter supports other custom UIs links as well.

stripe

Stripe public key, the example uses the test key pk_test_aThAAdvPHgIdAziZweywBWNk
This is the production one pk_live_Wdef2LjEQXsgFWult6IVFobB


Site

Pelcro.site.read()

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

Example

const siteData = window.Pelcro.site.read();

// full site object
console.log(siteData);

// site products
console.log(siteData.products);

// site logo
console.log(siteData.logo);

// site has ecommerce enabled
console.log(siteData.ecommerce_enabled);

Pelcro.site.getById(callbackFn)

Fetch the latest site data from Pelcro.

Example

window.Pelcro.site.getById((error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const siteData = response.data;
    console.log(siteData);
})

User

Pelcro.user.register(parameters, callbackFn)

Create a new user with an email and password. emits the PelcroUserRegister and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.register({
    email: "[email protected]",
    password: "123456",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

email

String

password

String

first_name

String

last_name

String

phone

String

display_name

String

title

String

salutation

String

metadata

Object

{
  registration_date: "12-11-2021"
}

Pelcro.user.login(parameters, callbackFn)

Logs in a registered user with an email and password. emits the PelcroUserLogin and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.login({
    email: "[email protected]",
    password: "123456",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

email

String

password

String


Pelcro.user.read()

Returns the authenticated user's data.

Example

const user = window.Pelcro.user.read();

// full user object
console.log(user);

// user email
console.log(user.email);

// user subscriptions
console.log(user.subscriptions);

// user addresses
console.log(user.addresses);

// user ecommerce orders
console.log(user.orders);

// user metadata object
console.log(user.metadata);

Pelcro.user.idpLogin(parameters, callbackFn)

Logs in a user using an identity provider. emits the PelcroUserLogin and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.idpLogin({
    idp_name: "facebook",
    idp_token: "abc1234",
    email: "[email protected]",
    first_name: "john",
    last_name: "doe",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

idp_name

String
"facebook" | "google" | "auth0"

idp_token

String

first_name

String

last_name

String

phone

String

display_name

String

title

String

salutation

String

metadata

Object

{
  registration_date: "12-11-2021"
}

Pelcro.user.update(parameters, callbackFn)

Update an existing user's profile. emits the PelcroUserUpdated and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.update({
    auth_token: window.Pelcro.user.read().auth_token,
    first_name: "John",
    last_name: "Doe",
    phone: "0123456",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

auth_token

String

first_name

String

last_name

String

phone

String

display_name

String

title

String

salutation

String

metadata

Object

{
  registration_date: "12-11-2021"
}

Pelcro.user.convert(parameters, callbackFn)

Convert a user without an email and password from an old provider with the old provider id. emits the PelcroUserRegister and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.convert({
    old_provider_id: 1234,
    email: "[email protected]",
    password: "123456",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

old_provider_id

number

email

String

password

String

first_name

String

last_name

String

metadata

Object

{
  registration_date: "12-11-2021"
}

Pelcro.user.logout(callbackFn)

Logs out the currently logged-in user. emits the PelcroUserLogout DOM events when the response is returned successfully.

Example

window.Pelcro.user.logout()

Pelcro.user.isAuthenticated()

check if the current user is logged in or not.

Example

window.Pelcro.user.isAuthenticated()

Pelcro.user.uploadProfilePicture(parameters, callbackFn)

Update a user's profile picture. emits the PelcroUserUpdated and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.uploadProfilePicture({
    auth_token: window.Pelcro.user.read().auth_token,
    image: newProfilePictureBlob,
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const newPictureLink = response.data.profile_photo;
    console.log(newPictureLink);
})

Pelcro.user.removeProfilePicture(parameters, callbackFn)

Remove a user's profile picture. emits the PelcroUserUpdated and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.removeProfilePicture({
    auth_token: window.Pelcro.user.read().auth_token,
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.user.saveToMetaData(parameters, callbackFn)

Save a key-value pair to user's metadata. emits the PelcroMetadataUpdated DOM events when the response is returned successfully.

Example

window.Pelcro.user.saveToMetaData({
    auth_token: window.Pelcro.user.read().auth_token,
    key: "savedArticlesIds",
    value: [14,15,88]
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const userMetaData = response.data.metadata;
    console.log(userMetaData);
})

Pelcro.user.hasOrdered(skuId)

Check if the user ordered a specific e-commerce SKU.

Example

const skuIdToCheck = 1234
window.Pelcro.user.hasOrdered(skuIdToCheck)

Pelcro.user.isEntitledTo(entitlementName)

Check if the user is entitled to a certain entitlement.

Example

const PremiumContentEntitlement = "premium"
const shouldShowPremiumContent  = window.Pelcro.user.isEntitledTo(PremiumContentEntitlement)

Pelcro.user.resendEmailVerification(callbackFn)

Resend the email verification message to the user's email address. Emits the PelcroUserUpdated and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.resendEmailVerification((error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.user.verifyEmailToken(parameters, callbackFn)

Verify the user's email using the token that was sent to their email address. Emits the PelcroUserUpdated and PelcroUserLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.user.verifyEmailToken({
    token: "example_token_123",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Subscription

Pelcro.subscription.create(parameters, callbackFn)

Create a new subscription for the current user. emits the PelcroSubscriptionCreate DOM events when the response is returned successfully.

Example

const selectedPaymentMethodId = 1234

window.Pelcro.subscription.create({
    auth_token: window.Pelcro.user.read().auth_token,
    source_id: selectedPaymentMethodId,
    payment_gateway: "stripe",
    gateway_token: "example_token",
    campaign_key: "my_promotion",
    plan_id: 123,
    address_id: 123,
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

auth_token

string

source_id

number

payment_gateway

string
"stripe" | "braintree"

gateway_token

string

address_id

number

plan_id

number

coupon_code

string

gift_recipient_first_name

string

gift_recipient_last_name

string

gift_recipient_email

string

gift_start_date

string
YYYY-MM-DD

gift_start_date: "2021-09-02"

gift_message

string

pay_via_send_invoice

boolean

quantity

number

domains

string[]

["example.com", "example2.com"]

ip_addresses

string[]

["192.168.1.1", "136.267.4.6"]

campaign_key

string


Pelcro.subscription.cancel(parameters, callbackFn)

Cancel an existing subscription for the current user. emits the PelcroSubscriptionCancel DOM events when the response is returned successfully.

Example

window.Pelcro.subscription.cancel({
    auth_token: window.Pelcro.user.read().auth_token,
    subscription_id: 123
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.subscription.reactivate(parameters, callbackFn)

Reactivate a canceled subscription for the current user.

Example

window.Pelcro.subscription.reactivate({
    auth_token: window.Pelcro.user.read().auth_token,
    subscription_id: 123
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.subscription.renew(parameters, callbackFn)

Renew an existing subscription for the current user.

Example

const selectedPaymentMethodId = 1234
const existingSubIdToRenew = 123

window.Pelcro.subscription.renew({
    auth_token: window.Pelcro.user.read().auth_token,
    source_id: selectedPaymentMethodId,
    payment_gateway: "stripe",
    gateway_token: "example_token",
    campaign_key: "my_promotion",
    plan_id: 123,
    address_id: 123,
    subscription_id: existingSubIdToRenew
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.subscription.renewGift(parameters, callbackFn)

Renew an existing gift subscription for another user as the donor.

Example

const selectedPaymentMethodId = 1234
const donatedSubscriptionIdToRenew = 123

window.Pelcro.subscription.renewGift({
    auth_token: window.Pelcro.user.read().auth_token,
    source_id: selectedPaymentMethodId,
    payment_gateway: "stripe",
    gateway_token: "example_token",
    plan_id: 123,
    address_id: 123,
    subscription_id: donatedSubscriptionIdToRenew
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.subscription.change(parameters, callbackFn)

Change an existing subscription for the current user.

Example

const existingSubIdToChange = "123"
const planIdToChangeTo = "123"

window.Pelcro.subscription.change({
    plan_id: planIdToChangeTo,
    address_id: "123",
    subscription_id: existingSubIdToChange
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Pelcro.subscription.redeemGift(parameters, callbackFn)

Redeem a gift code.

Example

window.Pelcro.subscription.redeemGift({
    gift_code: "123456",
    address_id: "123"
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }

    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

gift_code

string

address_id

string

subscription_id
used to redeem the gift as a future phase of an existing subscription

number


Pelcro.subscription.list()

List the subscriptions of the current user.

Example

window.Pelcro.subscription.list();

Pelcro.subscription.isSubscribedToPlan(parameters)

Check if the current user is subscribed to a specific plan.

Example

const isSubscribed = window.Pelcro.subscription.isSubscribedToPlan({ id:123 });
console.log(isSubscribed);

Pelcro.subscription.isSubscribedToSite()

Check if the current user is subscribed to any plan that isn't a donation plan.

Example

const isSubscribed = window.Pelcro.subscription.isSubscribedToSite();
console.log(isSubscribed);

Password

Pelcro.password.forgot(parameters, callbackFn)

Sends a password reset link to the passed email. emits the PelcroPasswordForgot DOM events when the response is returned successfully.

Example

window.Pelcro.password.forgot({
      email: "[email protected]",
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Pelcro.password.reset(parameters, callbackFn)

Used to finish the password reset flow to update the user's password. the required reset token can be found in the reset link's query parameters. which can be requested using the Pelcro.password.forgot function. emits the PelcroPasswordReset DOM events when the response is returned successfully.

Example

window.Pelcro.password.reset({
      email: "[email protected]",
      password: "123456",
      password_confirmation: "123456",
      token: "abc12345xyz"
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Pelcro.password.update(parameters, callbackFn)

update the current user's password. emits the PelcroPasswordUpdate DOM events when the response is returned successfully.

Example

window.Pelcro.password.update({
      old_password: "123456",
      new_password: "123abc",
      confirm_new_password: "123abc"
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Address

Pelcro.address.create(parameters, callbackFn)

Create a new address for the current user. emits the PelcroAddressCreated DOM events when the response is returned successfully.

Example

window.Pelcro.address.create({
      type: "shipping",
      first_name: "john",
      last_name: "doe",
      title: "mr",
      company: "abc",
      department: "operations",
      line1: "4 kingston street",
      line2: "apt 15",
      city: "San Francisco",
      state: "CA",
      country: "US",
      postal_code: "12345"
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

type

String
"shipping" | "billing"

title

String

first_name

String

last_name

String

phone

String

company

String

department

String

line 1

String

line 2

string

city

string

state

string

country

string


Pelcro.address.update(parameters, callbackFn)

update an existing address for the current user. emits the PelcroAddressUpdated DOM events when the response is returned successfully.

Example

window.Pelcro.address.update({
      address_id: 123,
      type: "shipping",
      first_name: "john",
      last_name: "doe",
      title: "mr",
      company: "abc",
      department: "operations",
      line1: "4 kingston street",
      line2: "apt 15",
      city: "San Francisco",
      state: "CA",
      country: "US",
      postal_code: "12345"
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
 
    const user = response.data;
    console.log(user);
})

Parameter reference

Parameter

Type

address_id

number

type

String
"shipping" | "billing"

title

String

first_name

String

last_name

String

phone

String

company

String

department

String

line 1

String

line 2

string

city

string

state

string

country

string


Pelcro.address.list()

Get the list of the current user's addresses

const userAddresses = window.Pelcro.address.list();
console.log(userAddresses);

Ecommerce

Pelcro.ecommerce.products.list(callbackFn)

Manually fetch ecommerce products from our backend. emits the PelcroEcommerceProductsLoaded DOM events when the response is returned successfully.

Example

window.Pelcro.ecommerce.products.list((error, response) => {
    if (error) {
    return console.log("error", error.message);
  }
 
  const ecomProducts = response.data.products;
  console.log(ecomProducts);
});

Pelcro.ecommerce.products.read(callbackFn)

Get the list of ecommerce products.

Example

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

Pelcro.ecommerce.products.getByProductId(productId)

Get a specific ecommerce product by its id.

Example

const ecomProduct = window.Pelcro.ecommerce.products.getByProductId(123);

Pelcro.ecommerce.products.getBySkuId(SkuId)

Get a specific e-commerce SKU by its SKU id.

Example

const sku = window.Pelcro.ecommerce.products.getBySkuId(321);

Pelcro.ecommerce.order.create(parameters, callbackFn)

Create an ecommerce order for the current user. emits the PelcroOrderCreate DOM events when the response is returned successfully.

Examples

Create an order with a new payment source token.

window.Pelcro.ecommerce.order.create(
  {
    items: [
      {
        "sku_id": 34,
        "quantity": 1
      }
    ],
    payment_gateway: "stripe",
    gateway_token: "stripe_1234322111",
    address_id: 123,
    campaign_key: "my_promotion",
  },
  (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
    
    const order = response.data.order;
    console.log(order);
  }
);

Create an order with a saved payment source id.

window.Pelcro.ecommerce.order.create(
  {
    items: [
      {
        "sku_id": 34,
        "quantity": 1
      }
    ],
    source_id: 123456,
    address_id: 123
  },
  (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
    
    const order = response.data.order;
    console.log(order);
  }
);

Parameter reference

Parameter

Type

Description

items

array

[{
        "sku_id": 34,
        "quantity": 1    
}]

source_id

number

Use a user saved payment method as the payment source. Instead of a new card token.

// list of user saved payment methods
window.Pelcro.user.read().sources;

payment_gateway

string
"stripe" | "braintree"

gateway_token

string

address_id

number

coupon_code

string

campaign_key

string

The campaign associated to the order. If the key does not already exist, it will be created. The campaign key must be between 3 and 191 characters in length and include only letters, numbers, dashes and underscores without space.


Pelcro.ecommerce.order.createSummary(parameters, callbackFn)

Gets a summary of an ecommerce order.
Including calculating taxes and price after applying coupon.

Example

window.Pelcro.ecommerce.order.createSummary(
  {
    items: [
      {
        "sku_id": 34,
        "quantity": 1
      }
    ],
    coupon_code: "50off"
  },
  (error, response) => {
    if (error) {
            return console.log("error", error.message);
    }
    
    const summary = response.data;
    console.log(summary);    
  }
);

Parameter reference

Parameter

Type

items

array

[{
        "sku_id": 34,
        "quantity": 1    
}]

coupon_code

string


Payment source

Pelcro.source.create(parameters, callbackFn)

Creates a new user payment source using a stripe card token. emits the PelcroSourceCreated DOM events when the response is returned successfully.

Example

window.Pelcro.source.create(
  {
    auth_token: window.Pelcro.user.read().auth_token, 
    token: "stripe_token"
  },
  (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
    
    const createdSource = response.data.sources[response.data.sources.length - 1];
    console.log(createdSource);
  }
)

Parameter reference

Parameter

Type

auth_token

string

token

string


Pelcro.source.update(parameters, callbackFn)

Updates a stripe payment card expiry date. emits the PelcroSourceUpdated DOM events when the response is returned successfully.

Example

window.Pelcro.source.update(
  {
    auth_token: window.Pelcro.user.read().auth_token, 
    source_id: 1234,
    cc_exp: "01/25"
  },
  (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
    
    const userPaymentSources = response.data.sources;
    console.log(userPaymentSources);
  }
)

Parameter reference

Parameter

Type

auth_token

string

source_id

number

cc_exp

string


"01/25"


Product

Pelcro.product.list()

List all available products, filtered according to user's currency, location, and page language.

Example

const products = window.Pelcro.product.list();

console.log(products);

Pelcro.product.listByTarget()

List all products targeting the current user.

Example

const targetedProducts = window.Pelcro.product.listByTarget();

console.log(targetedProducts);

Pelcro.product.getById(productId)

Get a specific product by id.

Example

const product = window.Pelcro.product.getById(123);

console.log(product);

Pelcro.product.getByEntitlements(entitlementsArray)

Get products with plans that at least match with one entitlement in the entitlementsArray argument.

Example

window.Pelcro.product.getByEntitlements(["gold", "silver"])

Plan

Pelcro.plan.getById(planId)

Get a specific plan by id.

Example

const plan = window.Pelcro.plan.getById(123);

console.log(plan);

Pelcro.plan.getByIP(callbackFn)

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

Example

window.Pelcro.plan.getByIP((error, response) => {
    if (error) {
    return console.log("error", error.message);
  }
  
  const plans = response;
  console.log(plans);
})

Pelcro.plan.getByEmail(parameters, callbackFn)

Get an array of plans associated with the user email address's domain.

Example

window.Pelcro.plan.getByEmail(
    { 
      email: "[email protected]" 
    },
    (error, resp) => {
            if (error) {
            return console.log("error", error.message);
      }
      
        const plans = response;
        console.log(plans);          
});

Pelcro.plan.getPlan(parameters, callbackFn)

Fetch a specific plan, including offline plans.

Example

window.Pelcro.plan.getPlan({
  plan_id: 123
}, (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const plan = response.data.plan;
  console.log(plan);
});

Parameter reference

Parameter

Type

plan_id

number


Order

Pelcro.order.create(parameters, callbackFn)

Gets a summary of a subscription order (before subscribing for a plan).
Including calculating taxes and price after applying coupon.

Example

window.Pelcro.order.create({
  auth_token: window.Pelcro.user.read().auth_token, 
  plan_id: 1234,
  address_id: 321,
  coupon_code: "50OFF"
}, (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const orderSummary = response.data.plan;
  console.log(orderSummary);
});

Parameter reference

Parameter

Type

auth_token

string

plan_id

number

address_id

number

coupon_code

string


Paywall

Pelcro.paywall.read()

Get the current active paywall.

Example

const activePaywall = window.Pelcro.paywall.read();
console.log(activePaywall);

Pelcro.paywall.getProduct()

Get the product linked with the active paywall.

Example

const paywallProduct = window.Pelcro.paywall.getProduct();
console.log(paywallProduct);

Pelcro.paywall.freeVisitsLeft()

Get the number of free visits left according to the targeted paywall.

Example

const visitsLeft = window.Pelcro.paywall.freeVisitsLeft();
console.log(visitsLeft);

Pelcro.paywall.displayNewsletterPaywall()

Returns a boolean that indicates whether the newsletter paywall should be displayed or not.

Example

const shouldDisplayNewsletterPaywall = window.Pelcro.paywall.displayNewsletterPaywall();
console.log(shouldDisplayNewsletterPaywall);

Pelcro.paywall.displayMeterPaywall()

Returns a boolean that indicates whether the meter paywall (Shows the number of free visits left) should be displayed or not.
True when a user still has free visits left.

Example

const shouldDisplayMeterPaywall = window.Pelcro.paywall.displayMeterPaywall();
console.log(shouldDisplayMeterPaywall);

Pelcro.paywall.displayPaywall()

Returns a boolean that indicates whether the blocking paywall should be displayed or not.
True when a user had used all free visits allowed.

Example

const shouldDisplayPlansPaywall = window.Pelcro.paywall.displayPaywall();
console.log(shouldDisplayPlansPaywall);

Pelcro.paywall.isArticleRestricted()

Returns a boolean that indicates whether the user is authorized to view the current article based on the paywall rules set in the product configuration.

Example

const isArticleRestricted = window.Pelcro.paywall.isArticleRestricted();
console.log(isArticleRestricted);

Newsletter

Pelcro.newsletter.create(parameters, callbackFn)

Creates a new newsletter subscription for a specific email.

window.Pelcro.newsletter.create({
  email: "[email protected]",
}, (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const newsletter = response.data;
  console.log(newsletter);
});

Parameter reference

Parameter

Type

email

string

source

string

lists

string

postal_code

string

consent_url

string

consent_text

string

consent_type

string


Pelcro.newsletter.getByEmail(email, callbackFn)

Get the subscribed newsletter for a specific email.

window.Pelcro.newsletter.getByEmail("[email protected]", (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const orderSummary = response.data.plan;
  console.log(orderSummary);
});)

Pelcro.newsletter.update(parameters, callbackFn)

Update the newsletter subscription for a specific email.

window.Pelcro.newsletter.update({
  email: "[email protected]",
}, (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const newsletter = response.data;
  console.log(newsletter);
});

Parameter reference

Parameter

Type

email

string

source

string

lists

string

postal_code

string

consent_url

string

consent_text

string

consent_type

string


Pelcro.newsletter.isSubscribedToNewsletter()

Check if the user is subscribed to the newsletter

const isSubscribedToNewsletter = window.Pelcro.newsletter.isSubscribedToNewsletter();
console.log(isSubscribedToNewsletter);

Coupon

Pelcro.coupon.getFromUrl()

Gets the coupon passed in the current URL, comes from the "coupon_code" query parameter.

Example

const couponCode = window.Pelcro.coupon.getFromUrl();
console.log(couponCode);

Insight

🚧

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.

Pelcro.insight.track(eventName, options)

Programmatically capture event using code. In this example, an event named “Button clicked” is triggered.

Example

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

You can also add custom properties to the event.

Example

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

Default properties added with all captured events

  • 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

Pelcro.insight.getPlansRecommendations(parameters, callbackFn)

Plan recommendations per user powered by a neural network multi-class categorical probabilistic regression machine learning algorithm.

Example

window.Pelcro.insight.getPlansRecommendations(
  {
    user_id: 23221
  },
  (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const plansRecommendations = response;
  console.log(plansRecommendations);
});

Pelcro.insight.getSubscriptionPrediction(parameters, callbackFn)

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.

Example

window.Pelcro.insight.getSubscriptionPrediction(
  {
    user_id: 23221
  },
  (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const subPredictions = response;
  console.log(subPredictions);
});

Pelcro.insight.getChurnPrediction(parameters, callbackFn)

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.

Example

window.Pelcro.insight.getChurnPrediction(
  {
    user_id: 23221
  },
 (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const churnPredictions = response;
  console.log(churnPredictions);
});

Pelcro.insight.getContentRecommendations(parameters, callbackFn)

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

Example

window.Pelcro.insight.getContentRecommendations(
 {
   user_id: 23221,
 },
  (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const contentRecommendations = response;
  console.log(contentRecommendations);
});

Get the filtered and boosted by section content recommendations.

Example

window.Pelcro.insight.getContentRecommendations(
 {
   user_id: 23221,
   filter: ["filter", "tags"],
   boost: ["tags", "to", "boost"],
 },
 (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const contentRecommendations = response;
  console.log(contentRecommendations);
});

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

Example

window.Pelcro.insight.getContentRecommendations(
 {
   user_id: 23221,
   filter: ["filter", "tags"],
   boost: ["tags", "to", "boost"],
   boost_paywalled: true
 },
 (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const contentRecommendations = response;
  console.log(contentRecommendations);
});

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((error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

  const {disqus_auth_key, disqus_public_key} = response.data;
  console.log("disqus_auth_key", disqus_auth_key);
  console.log("disqus_public_key", disqus_public_key);
});

Helpers

Pelcro.helpers.getURLParameter(paramString)

Gets a specific URL parameter value from the current URL.

Example

const giftCode = window.Pelcro.helpers.getURLParameter("gift_code");
console.log(giftCode);

Pelcro.helpers.loadSDK(scriptURL, scriptId)

Loads a JS script into the document.

Example

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

Pelcro.helpers.loadCSS(stylesheetURL, stylesheetId)

Loads a css stylsheet into the document.

Example

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

Events

Listen to triggered events from the SDK and add your own reactions. 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.

Event triggered

Description

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.

PelcroUserRefresh

This occurs when a page is refreshed/loaded and a user is still authenticated on the Pelcro JS-SDK.

PelcroUserLogin

This occurs when a user logs in 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.

PelcroUserLogout

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

PelcroUserUpdated

This occurs when the user object is updated via 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.

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.


FAQ

What should I do if I want to use Pelcro's SDK only without the UI?

Simply replace the UI environment property with empty whitespace.

window.Pelcro.environment.ui = " ";

How do I deal with errors coming from calling Pelcro's SDK methods?

Requests will be validated by the API using server-side validations. Error messages returned by the API are accessible as follows:

window.Pelcro.user.login({
    email: "[email protected]",
    password: "INVALID_PASSWORD",
}, (error, response) => {
    if (error) {
        console.log("error", error.response.data.error.message); // "Invalid credentials! Please try again."
        console.log("error", error.response.data.error.status); // 404
    }
})

API status 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.


Did this page help you?