@mathereconomics/sophi-paywall-params-builder
v1.0.0
Published
Utility package to construct query parameters for requests to MatherEconomic's Sophi Dynamic Paywall API
Downloads
1
Readme
Overview
sophi-paywall-params-builder
facilitates creating request parameters for calls to Sophi Paywall API, which generates wall decisions.
Requirements
This lightweight package is suitable for JavaScript environments such as browsers, Node.js, or edge runtimes like Fastly Compute.
Usage
To create request parameters, pass in a set of user and content details along with a Bins
object retrieved from Sophi's CDN. Use the resulting parameters to obtain a paywall decision via Sophi's API.
Code Example
The following code snippet demonstrates how to utilize the package in a JavaScript environment to fetch a paywall decision. It illustrates the process from importing the necessary functions to making an API call to retrieve the decision based on user and content data.
// Import from package
import { prepareRequestParams } from "@mathereconomics/sophi-paywall-params-builder"
// Fetch bin file
const bin = await fetch("https://cdn.sophi.io/distributions/js/apps/abc123/paywall-bin.json")
.then(response => {
if (response.status === 200) return response.json()
})
// Create object with content and visitor data
const inputs = {
"content.id": "123",
"content.lastPublishedAt": "2024-04-26",
"page.section": "arts",
"page.url": "https://www.example.com/sports/nfl/draft-picks-announced/abc123/",
"visitor.visit.referrer": "https://google.com",
"visitor.type": "anonymous",
"visitor.isReturning": false,
"visitor.utcOffset": -500,
"visitor.device.type": "mobile",
"visitor.device.os": "iOS",
"visitor.device.viewer": "chrome"
}
// Pass input data and bin file to parameter builder
const search = prepareRequestParams(inputs, bin)
console.log(search instanceof URLSearchParams) // true
// Create URL for decisions endpoint
const hostname = "www.example.com" // replace with your hostname
const url = new URL(`https://paywall.sophi.io/hosts/${hostname}/decisions/me`)
// Append search parameters returned by prepareRequestParams to the URL
url.search = search
// Fetch a decision from the endpoint
const decision = await fetch(url).then(r => r.json())
Code Logic
Here's a detailed step-by-step breakdown of what the code snippet is doing:
- Import the Function: The code imports
prepareRequestParams
from the package@mathereconomics/sophi-paywall-params-builder
. This function is used to prepare the request parameters necessary for fetching a paywall decision. - Fetch Bins File: The code asynchronously fetches a bin file from Sophi's Content Delivery Network (CDN) using the URL provided (
https://cdn.sophi.io/distributions/js/apps/abc123/paywall-bin.json
). It waits for the response, checks if the status is 200 (OK), and then converts the response to JSON format, which represents the bin data. Note: Different hosts (www.site1.com, www.site2.com) may be using different bins files; make sure the bins file is being fetched from the right URL. - Create Data Object: An object named
inputs
is created, containing various pieces of information about the content and the visitor. This includes IDs, URLs, publication dates, visitor types, devices, and more. These inputs are necessary for making a context-aware decision. - Pass Input Data to Parameter Builder: The
inputs
object and thebin
data fetched from the CDN are passed to theprepareRequestParams
function. This function uses the data to generate URL search parameters suitable for querying the paywall decision endpoint. The output fromprepareRequestParams
is an instance ofURLSearchParams
. - Create URL for Paywall Decision Endpoint: A base URL for the paywall decision endpoint is constructed using a hostname (
www.example.com
). This should be replaced with the actual hostname of the site for which a decision is being generated. The search parameters created earlier are appended to the URL to complete the request URL. - Fetch Paywall Decision: Finally, the complete URL is used to make a GET request to the paywall decision endpoint. The response is awaited and then converted to JSON, which should contain the decision about whether to display a paywall to the user.
In summary, this code snippet illustrates the end-to-end process of fetching necessary data, processing it to fit the requirements of an API, and then querying that API to make a decision based on the inputs provided.
Reference
In the reference section below, you'll find detailed documentation for the API, which may include descriptions of endpoints, parameters, and sample requests. This information is designed to assist developers in understanding and integrating the API effectively into their applications.
prepareRequestParams()
/**
* @param {Inputs} inputs - Object containing data on user and content - see below
* @param {Bin} bin - Object fetched from Sophi CDN - see below
* @returns {URLSearchParams} - Instance of the JavaScript built-in interface
* @throws {ArgumentError | UnexpectedError} - See below
*/
function prepareRequestParams(inputs: Inputs, bin: Bin): URLSearchParams
Inputs
An Inputs
object consists of the following properties:
| Key | Description | Type | Example | Documentation |
|----------|----------|----------|----------|----------|
| content.id | Content ID as provided by the CMS | string, required | "123"
| API docs |
| page.section | Top-level section under which the page is published | string | "arts"
| API docs |
| visitor.type | Logged-in status of user | one of: "anonymous"
, "registered"
| "anonymous"
| API docs |
| visitor.isReturning | Flag indicating whether user has visited before | boolean | true
| API docs |
| visitor.device.type | Type of user's device | string | mobile
| API docs |
| visitor.device.os | Operating system of user's device | string | iOs
| API docs |
| visitor.device.viewer | User's browser | string | chrome
| API docs |
| content.lastPublishedAt | Date when the article was published | string | "2024-04-26"
| more |
| visitor.utcOffset | Integer representing offset versus UTC time | integer | -230
| more |
| page.url | Full URL of the page user is visiting | string | "https://www.example.com/
sports/nfl/draft-picks-
announced/abc123/"
| more |
| page.referrer | Full URL of the page user is coming from | string | "https://google.com"
| more |
Expanded Inputs
In the following section, we expand upon specific properties within the inputs object, providing additional context beyond what is presented in the table.
content.lastPublishedAt
Date of the article's original publication, not when the article was last updated, formatted as a string in YYYY-MM-DD.
Examples:
"2023-12-01"
"2019-02-02"
visitor.utcOffset
Offset from Coordinated Universal Time (UTC) expressed as a time zone difference. Values are three or four digit numbers in the format (-)HHMM or (-)HMM, where H is hours and M is minutes. Values may be negative.
Value must be one of: -1200
, -1100
, -1000
, -930
, -900
, -800
, -700
, -600
, -500
, -400
, -330
, -300
, -200
, -100
, 0
, 100
, 200
, 300
, 330
, 400
, 430
, 500
, 530
, 545
, 600
, 630
, 700
, 800
, 845
, 900
, 930
, 1000
, 1030
, 1100
, 1200
, 1245
, 1300
, 1400
Examples:
-500
- offset of minus five hours from UTC, New York standard time-330
- offset of minus three hours thirty minutes from UTC, St. John's standard time0
- offset in UTC time zone, London standard time900
- offset of plus nine hours in UTC time zone, Tokyo standard time
page.url
Full URL of the page that the user is visiting. Query string can be omitted.
Example:
https://www.news.com/section/article-title-slug/2023-12-01/articleId123
page.referrer
URL of the page that the user navigated from. Query string can be omitted.
Example:
https://www.facebook.com
Bins
A Bins
object is the return value of the Response.json
method called on the response to the Sophi CDN after fetching from the bin URL. Do not transform or modify this object before passing it to prepareRequestParams
.
:::(Info) If you are working with multiple hosts, for example www.site1.com and www.site2.com, make sure you are fetching the right bins file for each host. The URLs of bins files for each host may be different. :::
const bin: Bin = await fetch("https://cdn.sophi.io/distributions/js/apps/abc123/paywall-bin.json").then(r => r.json())
Errors
ArgumentError
- thrown if the format of the argument passed is incorrect- For example:
new Error("ArgumentError: expected bin to be an object, got string")
- For example:
UnexpectedError
- thrown if preparing parameters fails- For example:
new Error("UnexpectedError")
- For example: