Key squatch.js Scripts
JavaScript SDK
While I did not write the original material, I was involved heavily with consulting for accuracy and provided code samples. I also restructured and edited the entire article for coherency and accessibility.
You can view a “live” version of these scripts at my old repo here (seen in my original section Program loop): https://github.com/beckatimpact/squatch-js
For this endeavour I researched and familiarized myself with:
Any links to guides I did not author have been removed for this archived version below.
Key squatch.js Scripts
This page has a list of the key squatch.js scripts you may need for your implementation of a SaaSquatch program. These are general scripts meant for reference purposes.
Add your tenant- and program-specific information to ensure they function as intended. To generate your personalized code snippets, sign in to the Admin Portal and go to Settings > Install.
Loader script
This async loader script must be included on your website in order to call squatch.js to perform many functions, including creating cookies that will take care of referral attributions. The rest of the scripts on this page rely on the Loader script to be present as it is what retrieves the functionality of squatch.js and allows referral cookies to be dropped and retrieved.
!function(a,b){a("squatch","https://fast.ssqt.io/squatch-js@2",b)}(function(a,b,c){var d,e,f;c["_"+a]={},c[a]={},c[a].ready=function(b){c["_" + a].ready = c["_" + a].ready || [];c["_" + a].ready.push(b);},e=document.createElement("script"),e.async=1,e.src=b,f=document.getElementsByTagName("script")[0],f.parentNode.insertBefore(e,f)},this);Environment setup
The squatchToken JWT added here will be used for user upsert (when a user is created, when a widget loads) as well as for event tracking. The example below is a static value, but you should be dynamically generating it based on your user object as needed.
window.squatchTenant = "test_aym93okveuya4";
window.squatchToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoidXNlcklkIiwiYWNjb3VudElkIjoiYWNjb3VudElkIiwiZmlyc3ROYW1lIjoiU3F1YXRjaEpzIiwibGFzdE5hbWUiOiJVc2VyIiwiZW1haWwiOiJzcXVhdGNoanNAZXhhbXBsZS5jb20ifX0.E2_OHk84j7BeNtkn5v8q24htsvIrN6ecyXzoSuDlJb4";
// Below used for overriding default config values
window.squatchConfig = {
domain: "<domain>",
npmCdn: "<npmCdn>",
debug: <trueOrFalse>
}Widget scripts
Widget styles
squatch.js supports two widget styles: embedded and popup.
- Embedded widgets show up directly within your web page or app.
- Pop-up widgets are displayed in a modal window. When you use the
squatch-popupelement, any HTML within the children of the element will serve as a CTA for opening the popup.
Verified access widget
Verified access widgets provide a robust, in-app experience for your referral or loyalty participants. To protect your participants’ personal information, we recommend displaying this widget only to those who have signed in to your product.
The below code snippets display an in-app widget for a Referrer in a referral program with the ID example-program.
Embedded widget
<squatch-embed widget="p/example-program/w/referrerWidget"><div>Loading...</div></squatch-embed>Popup widget
<squatch-popup widget="p/example-program/w/referrerWidget"><button>Click me to show widget!</button></squatch-popup>Instant access widget
Instant access widgets give your participants a simple way to engage with your referral program–without signing into your product or service. They’re available for clients using the current version of the SaaSquatch platform (post-2019).
The below code snippets display a widget for a anonymous Referrer in a referral program with the ID example-program.
Embedded widget
<squatch-embed widget="p/example-program/w/websiteReferralWidget"><div>Loading...</div></squatch-embed>Popup widget
// Click to open button
<squatch-popup widget="p/example-program/w/websiteReferralWidget"><button>Click me!</button></squatch-popup>Auto-popup friend widget
In addition to the standard embedded and popup widget styles, instant access widgets allow for an automatic pop-up widget to appear whenever the landing page is loaded for Friend Widgets. Participants don’t need to interact with your landing page to trigger a widget load when Show automatically for referred friends is toggled in the program settings as long as the loader script is present.
Register participants script
Use squatch.api’s upsertUser method to create or update a user in your referral program without displaying a widget. For example, this method can be used to create a user in SaaSquatch when someone fills out a registration form.
When a cookie is present, squatch.js will also automatically attribute the referral when users are upserted without the need to pass in an explicit referral code.
If you are following along by testing the examples on this page, you’ll need to adjust the hardcoded squatchToken outlined in “Environment setup” for the below call to reflect the user object.
// Wait for `squatch.js` to be ready
squatch.ready(function(){
// Configure squatch-js for your user
const userConfig = {
user: {
id: 'sample.user@example.com',
accountId: 'sample.user@example.com',
email: 'sample.user@example.com',
firstName: 'Sample',
lastName: 'User',
locale: 'en_US',
customFields: {
companyName: "Example Inc.",
phoneNumber: "(555) 340-0505"
}
}
};
// Make the request to upsert your user
squatch.api().upsertUser(userConfig).then(function(response) {
const user = response.user;
}).catch(function(error){
console.log(error);
});
});Autofill script
You can then “autofill” an element with the value, such as a referral code field in a sign-up form. There are many methods to accomplish this, such as:
getElementbyId: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementByIdgetElementsByClassName: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassNamegetElementsByTag: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
Referral codes
- The request to retrieve the information from the dropped cookie returns referral codes within an object called “codes”.
- This object is key value pair where the key is the program ID and the value is the referral code.
- You’ll need to use your referral program’s ID to access and apply the correct referral code to your element.
If you want to learn more about using autofill for multiple referral programs, then check out our autofill guide.
Cookie values
- Cookies are dropped after a user clicks on a sharelink.
- This cookie includes important referral analytics information and should be passed along with REST API & GraphQL API calls if you are not upserting users/attributing users automatically with
squatch.js.
To read more on our referral cookies see: /developer/squatchjs/cookies/
Autofill a referral code
Use cases:
- Displaying the referral code in a sign-up form field to your new user to confirm that a referral is taking place.
- Using the retrieved referral code to perform a Get a user by referral code REST API call to show the Referrer’s details to the Referred User.
- Retrieved then applied as a discount/coupon code with our HubSpot, Stripe and Recurly integrations.
// Wait for `squatch.js` to be ready
squatch.ready(function(){
// Retrieve the element you want to autofill the Referral Code into from the DOM.
var code = document.getElementById('referralCode');
// Make the request to retrieve the information from the dropped cookie
squatch.api().squatchReferralCookie().then(function(response) {
// Use your referral program id to access and apply the correct referral code to your element
code.value = response.codes["example-program"];
});
});Track user event script
You can use squatch.js to send user events directly to SaaSquatch, such as during a check-out action via the squatch.events’s track method.
If you are following along by testing the examples on this page, you’ll need to adjust the hardcoded squatchToken outlined in “Environment setup” for the below call to reflect the user object.
// Wait for `squatch.js` to be ready
squatch.ready(function(){
// Object containing the user & event object
var eventObj = {
"userId": "sample.user@example.com",
"accountId": "sample.user@example.com",
"events": [{
"key": "purchase",
"fields":{
"checkout_id": "123456",
"order_id": "234567",
"total": 100,
"revenue": 40,
"tax": 15,
"currency": "USD",
"products": [ {
"product_id": "p_name",
"name": "Product Name",
"price": 85,
"quantity": 1
}]
}
}]
};
// If window.squatchToken is not set, pass in a jwt with .track(eventObj, { jwt }), otherwise include the {squatchToken}
squatch.events().track(eventObj, {squatchToken}).then(function(response) {
}).catch(function(error){
console.log(error);
})
});Authentication
The requirement for including a JWT in the request can be removed by disabling the Track User Event option on the Settings > Security page. If you choose not to include a JWT, then you MUST use an empty JSON object ({}) instead of excluding that value.
Program loop
See a sample referral program as outlined on this page’s scripts in action: Sample Referral Program Code
The sample program includes use of:
squatch.api().upsertUser()squatch.api().squatchReferralCookie()- Embedded “Verified access widget”
squatch.events().track()- Embedded “Instant access widget”
Learn more
Error codes
We maintain an Issue Code List with details and specific troubleshooting tips for any error codes that you may receive. If you try out the troubleshooting steps and are still experiencing problems, then don’t hesitate to reach out to our Support team for assistance.
Additional documentation
- Advanced Use Cases: Go beyond the basic scripts and learn how to reference existing user data, render a widget without requiring user information, and more.
- Signed Requests: Learn how to require a JWT or an API key when sending data to SaaSquatch.
- Tracking Cookies: Learn more about
squatch.jsand first-party cookies. - Issue Code List: Find details and troubleshooting steps about error codes you encounter.
squatch.jsReference: Full list of methods available.