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

ParameterDescription
siteidYour Pelcro site id.
domainThe 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.
uiThe 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.
stripeStripe 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

ParameterType
email String
password String
usernameString
first_nameString
last_nameString
phoneString
display_name String
titleString
salutationString
organizationString
metadataObject


{ registration_date: "12-11-2021" }

Pelcro.user.login(parameters, callbackFn)

Logs in a registered user with an email and password. emits the PelcroUserLoggedIn 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

ParameterType
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

ParameterType
idp_name String
"facebook" | "google" | "auth0"
idp_token String
first_nameString
last_nameString
phoneString
display_name String
titleString
salutationString
metadataObject


{ 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,
  	email: "[email protected]",
    first_name: "John",
    last_name: "Doe",
    phone: "0123456",
  	display_name: "JohnDoe",
}, (error, response) => {
    if (error) {
    	return console.log("error", error.message);
    }

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

Parameter reference

ParameterType
auth_token String
first_nameString
last_nameString
phoneString
display_name String
titleString
salutationString
organizationString
metadataObject


{ 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

ParameterType
old_provider_id number
email String
password String
first_nameString
last_nameString
metadataObject


{ 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, PelcroEmailVerified, 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);
})

Pelcro.user.verifyLoginToken(parameters, callbackFn)

Verify the passwordless token using the token in the magic link that was sent to their email address. Emits the PelcroUserLoaded and PelcroUserUpdated DOM events when the response is returned successfully.

Example

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

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

Pelcro.user.requestLoginToken(parameters, callbackFn)

Takes a user's email to generate the magic link to be sent to the user's email.

Example

window.Pelcro.user.requestLoginToken({
    email: "[email protected]",
}, (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,
  	quantity: 1,
}, (error, response) => {
    if (error) {
    	return console.log("error", error.message);
    }

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

Parameter reference

ParameterType
auth_token string
source_id number
payment_gateway string
"stripe" | "braintree"
gateway_token string
address_id number
plan_id number
coupon_codestring
gift_recipient_first_namestring
gift_recipient_last_namestring
gift_recipient_emailstring
gift_start_datestring
YYYY-MM-DD

gift_start_date: "2021-09-02"
gift_messagestring
pay_via_send_invoiceboolean
quantitynumber
domainsstring[]

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

["192.168.1.1", "136.267.4.6"]
campaign_keystring

Pelcro.subscription.cancel(parameters, callbackFn)

Cancel an existing subscription for the current user. Emits the PelcroSubscriptionCancel DOM event 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. Emits the PelcroSubscriptionReactivated DOM event when the response is returned successfully.

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. Emit the PelcroSubscriptionRenewed DOM event when the response is returned successfully.

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,
  	quantity: 1
}, (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.update(parameters, callbackFn)

  • Suspend or unsuspend shipments for a subscription.
  • Add email domains / IP addresses to the subscription. Whenever an end-user registers/logs in with the same email domain or IP address, they will become a member of this subscription.

Example

const futureDate = "2030-07-25"

window.Pelcro.subscription.update({
    subscription_id: 2516554,
    suspend: true,
    shipments_suspended_until: futureDate
}, (error, response) => {
    if (error) {
    	return console.log("error", error.message);
    }

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

Parameter reference

auth_token string
subscription_id number
shipments_suspended_until string
YYYY-MM-DD
domainsstring[]

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

["192.168.1.1", "136.267.4.6"]
metadataObject


{ registration_date: "12-11-2021" }

Pelcro.subscription.redeemGift(parameters, callbackFn)

Redeem a gift code. Emit the PelcroGiftRedeemed DOM event when the response is returned successfully.

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

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

Pelcro.subscription.listMembers(parameters, callbackFn)

List members of the subscription.

Example

const subscriptionID = 2552828

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

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

Pelcro.subscription.inviteMembers(parameters, callbackFn)

Invite members to the subscription.

Example

const subscriptionID = 2552828

window.Pelcro.subscription.inviteMembers({
    auth_token:Pelcro.user.read().auth_token,
    subscription_id: subscriptionID,
  	emails: ["@example.com", "@example2.com"]
}, (error, response) => {
    if (error) {
    	return console.log("error", error.message);
    }

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

Pelcro.subscription.removeMember(parameters, callbackFn)

Remove a member from the subscription.

Example

const subscriptionID = 2552828
const memberID = 2354658

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

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

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

Parameter reference

ParameterType
type String
"shipping" | "billing"
titleString
first_name String
last_name String
phoneString
companyString
departmentString
line 1 String
line 2string
citystring
statestring
country string
is_defaultboolean

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

Parameter reference

ParameterType
address_id number
type String
"shipping" | "billing"
titleString
first_name String
last_name String
phoneString
companyString
departmentString
line 1 String
line 2string
city string
state string
country string
is_defaultboolean

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

ParameterTypeDescription
items array


[{ "sku_id": 34, "quantity": 1 }]
source_idnumberUse 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_gatewaystring
"stripe" | "braintree"
gateway_tokenstring
address_idnumber
coupon_codestring
campaign_keystringThe 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

ParameterType
items array


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

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

ParameterType
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

ParameterType
auth_token string
source_id number
cc_exp string


"01/25"

Payment methods

Pelcro.paymentMethods.create(parameters, callbackFn)

Creates a new user payment method using a stripe token. Emits the PelcroPaymentMethodCreated DOM events when the response is returned successfully.

Example

window.Pelcro.paymentMethods.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

ParameterType
auth_token string
token string
gateway (Required for gateways other than Stripe)string

Pelcro.paymentMethods.deletePaymentMethod(parameters, callbackFn)

Deletes a stored payment method using the payment method id. Emits the PelcroPaymentMethodDeleted DOM events when the response is returned successfully.

Example

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

    // No response if success
  }
);

Parameter reference

ParameterType
auth_token string
payment_method_id number

Pelcro.paymentMethods.update(parameters, callbackFn)

Updates a payment method's details using payment method id and other parameters that differs based on the gateway. Emits the PelcroPaymentMethodUpdated DOM events when the response is returned successfully.

Example for Stripe gateway

window.Pelcro.paymentMethods.update(
  {
    auth_token: window.Pelcro.user.read().auth_token,
    payment_method_id: 1234,
    gateway: "stripe",
    exp_month: 08,
    exp_year: 2029,
    is_default: true,
  },
  (error, response) => {
    if (error) {
      return console.log("error", error.message);
    }

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

Parameter reference for Stripe

ParameterType
auth_token string
payment_method_id number
gateway string
exp_month number
exp_year number
is_defaultboolean

Example for Vantiv gateway

window.Pelcro.paymentMethods.update(
  {
    auth_token: window.Pelcro.user.read().auth_token,
    payment_method_id: 1234,
    gateway: "vantiv",
    paypageRegistrationId: paypageRegistrationId,
    bin: bin,
    type: "MC",
    firstSix: 526489,
    lastFour: 4444,
    exp_month: 08,
    exp_year: 2029,
    is_default: true,
  },
  (error, response) => {
    if (error) {
      return console.log("error", error.message);
    }

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

Parameter reference for Vantiv

ParameterType
auth_token string
payment_method_id number
gateway string
exp_month number
exp_year number
is_defaultboolean
paypageRegistrationId string
bin string
type string
firstSix number
lastFour number

Pelcro.paymentMethods.getPaymentMethod(parameters, callbackFn)

Retrieve information about a specific payment method using the payment method id.

Example

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

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

Parameter reference

ParameterType
auth_token string
payment_method_id number

Pelcro.paymentMethods.list(parameters, callbackFn)

Lists the payment methods existing for the user.

Example

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

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

Parameter reference

ParameterType
auth_token string

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 = resp;
  		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

ParameterType
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

ParameterType
auth_token string
plan_id number
address_idnumber
coupon_codestring

Invoice

Pelcro.invoice.list()

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

Example

const invoices = window.Pelcro.invoice.list();

console.log(invoices);

Pelcro.invoice.pay(parameters, callbackFn)

Mark an invoice as paid. This will automatically charge the customer for the full amount. Emits the invoicePay DOM event when the response is returned successfully.

Example

window.Pelcro.invoice.pay({
  source_id: 12155,
  payment_gateway: 'payment_gateway',
  gateway_token: 'gateway_token'
}, (error, response) => {
  if (error) {
    return console.log("error", error.message);
  }

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

Parameter reference

ParameterTypeDescription
source_idnumberThe unique identifier of user's payment source, to be used for charging user
payment_gatewaystringRequired with gateway_token if source_id is not set

Options:
'stripe', 'braintree', or 'vantiv'
gateway_tokenstringRequired with payment_gateway if source_id is not set

Membership

Pelcro.membership.getByIP(callbackFn)

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

Example

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

Pelcro.membership.getByEmail(parameters, callbackFn)

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

Example

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

Campaign

Pelcro.campaign.getByID(callbackFn)

Gets campaign object by campaign ID

Example

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

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

Parameter reference

ParameterType
auth_token String
campaign_id Number

Pelcro.campaign.getByKey(callbackFn)

Gets campaign object by campaign Key

Example

window.Pelcro.campaign.getByKey({
    auth_token: window.Pelcro.user.read().auth_token,
    campaign_key: 1,
}, (error, response) => {
    if (error) {
        return console.log("error", error.message);
    }
    const campaign = response.data;
    console.log(campaign);
})

Parameter reference

ParameterType
auth_token String
campaign_key Number

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

Returns a boolean that indicates whether the blocking paywall should be displayed or not.
True when a user had used all free visits allowed.
dispatchPaywallDisplayedEvent default value is true, passing it as false will not Emit the PelcroPaywallDisplayed DOM event.

Example

const shouldDisplayPlansPaywall = window.Pelcro.paywall.displayPaywall(false);
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. Emits the PelcroNewsletterCreated DOM events when the response is returned successfully.

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

ParameterType
email string
sourcestring
listsstring
postal_codestring
consent_urlstring
consent_textstring
consent_typestring

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

ParameterType
email string
sourcestring
listsstring
postal_codestring
consent_urlstring
consent_textstring
consent_typestring

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 triggeredDescription
PelcroSiteLoadedThis occurs when the site configuration has been loaded in the JS-SDK and hence window.Pelcro.site.read(); is now available.
PelcroUserRegisterThis occurs when a user registers using the Pelcro JS-SDK.
PelcroUserRefreshThis occurs when a page is refreshed/loaded and a user is still authenticated on the Pelcro JS-SDK.
PelcroUserLoggedInThis occurs when a user logs in using the Pelcro JS-SDK, and includes the user object in the event detail.
PelcroUserLoadedThis occurs when the user object is updated via the Pelcro JS-SDK using the most up-to-date data from the API.
PelcroUserLogoutThis occurs when a user logs out using the Pelcro JS-SDK.
PelcroUserUpdatedThis occurs when the user object is updated via the Pelcro JS-SDK.
PelcroEmailVerifiedThis occurs when a user verifies their email using the Plecro JS-SDK, and includes the user object in the event detail.
PelcroSubscriptionCreateThis occurs when a subscription is created using the Pelcro JS-SDK.
PelcroSubscriptionRenewedThis occurs when a subscription is renewed using the Pelcro JS-SDK
PelcroSubscriptionCancelThis occurs when a subscription is canceled using the Pelcro JS-SDK.
PelcroSubscriptionReactivatedThis occurs when a subscription is reactivated using the Pelcro JS-SDK
PelcroGiftRedeemedThis occurs when you use a valid coupon while using the Pelcro JS-SDK
PelcroAddressCreatedThis occurs when the user's address object is created via the Pelcro JS-SDK.
PelcroAddressUpdatedThis occurs when the user's address object is updated via the Pelcro JS-SDK.
PelcroSourceCreatedThis occurs when the user's payment source object is created via the Pelcro JS-SDK.
PelcroPasswordForgotThis occurs when the password forgot is requested via the Pelcro JS-SDK.
PelcroPasswordResetThis occurs when the password gets reset via the Pelcro JS-SDK.
PelcroEcommerceProductsLoadedThis 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.
PelcroOrderCreatedThis occurs when a successful e-commerce order is created by a user and includes the order object in the event detail.
PelcroPaywallMatchThis 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.
PelcroPaywallDisplayedThis occurs when paywall is displayed and the displayPaywall method return true.
PelcroNewsletterCreatedThis occurs when you create a newsletter using Pelcro JS-SDK
PelcroPaywallNotDisplayedThis occurs when paywall is not displayed and displayPaywall method return false.

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.