### Install Conversions API Parameter Builder Python
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Install the library using pip. Verify the installation by listing installed packages.
```bash
pip install capi_param_builder_python
```
```bash
pip list
```
--------------------------------
### Install Conversions API Parameter Builder
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Add the Conversions API parameter builder NodeJS package to your project's dependencies. Run npm install to complete the setup.
```json
"dependencies": {
"capi-param-builder-nodejs": {version}
}
```
--------------------------------
### Install Dependencies
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Installs project dependencies using Yarn after navigating to the `client_js` directory.
```bash
cd client_js
yarn install
```
--------------------------------
### Start Local Development Server
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Start a local PHP development server on port 8000. This is used to run the demo application.
```bash
php -S localhost:8000
```
--------------------------------
### Install CapiParamBuilderRuby
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Install the library using the RubyGems package manager.
```bash
gem install capi_param_builder_ruby
```
--------------------------------
### Run Demo Application
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Navigate to the example directory and run the demo application using Ruby.
```bash
cd ./example
ruby app.rb
```
--------------------------------
### Install Composer Dependencies
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Install or update project dependencies using Composer. This command fetches the packages listed in your composer.json file.
```bash
composer install
```
```bash
composer update
```
--------------------------------
### Run Demo Application
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Execute the demo application using Gradle. This command starts the Spring Boot application for testing.
```bash
./gradlew bootRun
```
--------------------------------
### Install Package via Yarn
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Use this command to add the Conversions API parameter builder to your project using Yarn.
```bash
yarn add meta-capi-param-builder-clientjs
```
--------------------------------
### Verify CapiParamBuilderRuby Installation
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Verify the installation by checking if the gem is listed in your installed gems.
```bash
gem list | grep capi_param_builder_ruby
```
--------------------------------
### Node.js Test Command
Source: https://github.com/facebook/capi-param-builder/blob/main/AGENTS.md
Run this command to install dependencies and execute tests for the Node.js implementation. Tested on Node.js versions 18.x, 20.x, 22.x, and 24.x.
```bash
cd nodejs/capi-param-builder
npm install
npm test
```
--------------------------------
### Import ParamBuilder Class
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Import the necessary ParamBuilder class from the SDK. This is the first step after installing the library.
```java
import com.facebook.capi.sdk.ParamBuilder;
```
--------------------------------
### Maven Dependency Setup
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Configure your Maven project's pom.xml to include the Conversions API parameter builder. Replace {current_version} with the actual latest version.
```xml
com.facebook.capi.sdk
capi-param-builder
{current_version}
```
--------------------------------
### Initialize ParamBuilder with custom resolver
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Initialize ParamBuilder with a customized ETLD+1 resolver. An example implementation is available in ./resolver/default_etld_plus_one_resolver.py.
```python
paramBuilder = ParamBuilder(DefaultEtldPlusOneResolver())
```
--------------------------------
### Get Cookies to Set (from context)
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Retrieve the cookies to be set, typically obtained after calling `processRequestFromContext`.
```php
$cookie_to_set = $param_builder->processRequestFromContext();
```
--------------------------------
### Save Cookies from processRequestFromContext
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Example of saving the recommended cookies obtained from processRequestFromContext as first-party cookies.
```javascript
// Call processRequestFromContext in above step 3.
// The returned cookiesToSet is the recommended list of cookies to be saved.
const cookiesToSet = builder.processRequestFromContext(req);
for (const cookie of cookiesToSet) {
responseCookies.push(cookie.name + '=' + cookie.value + '; Max-Age=' + cookie.maxAge + '; Domain=' + cookie.domain + '; Path=/');
}
res.setHeader('Set-Cookie', responseCookies);
```
--------------------------------
### Gradle Dependency Setup
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Add the Conversions API parameter builder to your project's Gradle dependencies. Ensure you replace {current_version} with the latest version number.
```gradle
dependencies {
implementation 'com.facebook.capi.sdk:capi-param-builder:{current_version}'
}
```
--------------------------------
### Save cookies using get_cookies_to_set
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Example of saving recommended cookies obtained from paramBuilder.get_cookies_to_set(). Ensure process_request_from_context is called first.
```python
# process_request_from_context should be always called
paramBuilder.process_request_from_context(request)
for cookie in paramBuilder.get_cookies_to_set():
self.send_header( "Set-Cookie",
f"{cookie.name}={cookie.value};Max-Age={cookie.max_age};path=/;domain={cookie.domain}",)
```
--------------------------------
### Get Normalized and Hashed PII
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
API to get normalized and hashed (sha256) PII. Supported data types include 'phone', 'email', 'first_name', 'last_name', 'date_of_birth', 'gender', 'city', 'state', 'zip_code', 'country', and 'external_id'.
```javascript
getNormalizedAndHashedPII(piiValue, dataType)
```
--------------------------------
### Get referrer_url Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Retrieve the referrer_url parameter using the getReferrerUrl() method.
```javascript
const referrerUrl = builder.getReferrerUrl();
```
--------------------------------
### Get client_ip_address Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Retrieve the client_ip_address parameter using the getClientIpAddress() method.
```javascript
const client_ip_address = builder.getClientIpAddress();
```
--------------------------------
### Get referrer_url parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Retrieve the referrer_url parameter using the get_referrer_url() method.
```python
referrer_url = paramBuilder.get_referrer_url()
```
--------------------------------
### Format Data for Conversions API
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Example structure for sending parameters to the Conversions API, including event-level and user-data parameters.
```javascript
data=[
'event_name': '...',
'event_time': ,
'event_source_url': eventSourceUrl, // The value provided in step 5
'referrer_url': referrerUrl, // The value provided in step 5
'user_data': {
'fbc': fbc, // The value provided in step 5
'fbp': fbp, // The value provided in step 5
'client_ip_address': client_ip_address // The value provided in step 5
'em': email // The value provided in step 5
'ph': phone // The value provided in step 5
...
}
...
]
```
--------------------------------
### Ruby Test Command
Source: https://github.com/facebook/capi-param-builder/blob/main/AGENTS.md
Install the minitest gem and execute tests for the Ruby implementation. Tested on Ruby versions 3.0, 3.2, and 3.3.
```bash
cd ruby/capi_param_builder
gem install minitest
ruby -Ilib:test test/test_param_builder.rb
```
--------------------------------
### Get referrer URL
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Retrieve the referrer URL, which indicates the previous page the user visited.
```ruby
referrer_url = builder.get_referrer_url()
```
--------------------------------
### Get event_source_url parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Retrieve the event_source_url parameter using the get_event_source_url() method.
```python
event_source_url = paramBuilder.get_event_source_url()
```
--------------------------------
### Get event_source_url Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Retrieve the event_source_url parameter using the getEventSourceUrl() method.
```javascript
const eventSourceUrl = builder.getEventSourceUrl();
```
--------------------------------
### Install Conversions API Parameter Builder PHP
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Add the Conversions API parameter builder PHP package to your project's composer.json file. Ensure your PHP version is compatible.
```json
{
"require": {
"php": ">=7.4",
"facebook/capi-param-builder-php": "{current_version}"
}
}
```
--------------------------------
### Save cookies using process_request_from_context result
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Example of saving recommended cookies obtained from process_request_from_context. This ensures consistent fbc and fbp values.
```python
# Get the recommended saved cookie from step 4 API
updated_cookies = paramBuilder.process_request_from_context(request)
for cookie in updated_cookies:
self.send_header( "Set-Cookie",
f"{cookie.name}={cookie.value};Max-Age={cookie.max_age};path=/;domain={cookie.domain}",)
```
--------------------------------
### Format data for Conversions API
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Example structure for sending data to the Conversions API, including event details and user data with fbc and fbp.
```json
data=[
'event_name': '...',
'event_time': ,
'event_source_url': event_source_url, # The value provided in step 6
'referrer_url': referrer_url, # The value provided in step 6
'user_data': {
'fbc': fbc, # The value provided in step 6
'fbp': fbp, # The value provided in step 6
...
}
...
]
```
--------------------------------
### Get referrerUrl Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Retrieves the referrerUrl parameter, which is the URL of the referring page, from the ParamBuilder instance.
```java
String referrerUrl = paramBuilder.getReferrerUrl();
```
--------------------------------
### Get eventSourceUrl Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Retrieves the eventSourceUrl parameter, which is the URL where the event originated, from the ParamBuilder instance.
```java
String eventSourceUrl = paramBuilder.getEventSourceUrl();
```
--------------------------------
### Get Event Source URL
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Retrieve the URL from which the event originated. This helps in understanding the user's journey.
```php
$event_source_url = $param_builder->getEventSourceUrl();
```
--------------------------------
### Initialize ParamBuilder with Custom Resolver
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Initialize ParamBuilder using a custom logic for resolving etld+1. Refer to the example DefaultETLDPlus1Resolver.js for a demonstration.
```javascript
// Option 2: Resolve customized etld+1 via customized logic
// Check example DefaultETLDPlus1Resolver.js under example/util folder for demo.
const etldPlus1Resolver = new DefaultETLDPlus1Resolver();
const builder = new ParamBuilder(etldPlus1Resolver);
```
--------------------------------
### Custom IP Address Retrieval Function
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Example implementation of `getIpFn` for retrieving client IP addresses. This specific implementation uses an external API and is for demonstration purposes only; implement your own logic for production.
```javascript
const getIpFn = async () =>
(await fetch('https://api64.ipify.org')).text();
await clientParamBuilder.processAndCollectAllParams(null, getIpFn);
```
--------------------------------
### PHP Test Command
Source: https://github.com/facebook/capi-param-builder/blob/main/AGENTS.md
Install development dependencies and run PHPUnit tests for the PHP implementation. Tested on PHP versions 7.4, 8.0, 8.1, 8.2, 8.3, and 8.4.
```bash
cd php/capi-param-builder
composer install --dev --prefer-source
./vendor/bin/phpunit ./tests/ --debug
```
--------------------------------
### Get event source URL
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Retrieve the event source URL, which is important for tracking the origin of the event.
```ruby
event_source_url = builder.get_event_source_url()
```
--------------------------------
### Get fbp parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Retrieve the fbp (Facebook Pixel ID) parameter using the get_fbp() method.
```python
fbp = paramBuilder.get_fbp()
```
--------------------------------
### Get Cookies to Set (optional API)
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
An alternative method to retrieve cookies that need to be set. This might be used if you are not directly processing a request context.
```php
$cookie_to_set = $param_builder->getCookiesToSet()
```
--------------------------------
### Send Parameters to Conversions API
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Example structure for sending event data, including event-level parameters like eventSourceUrl and referrerUrl, and user_data parameters like fbc and fbp, to the Conversions API.
```json
data=[
'event_name': '...',
'event_time': ,
'event_source_url': eventSourceUrl, // The value provided in step 6
'referrer_url': referrerUrl, // The value provided in step 6
'user_data': {
'fbc': fbc, // The value provided in step 6
'fbp': fbp, // The value provided in step 6
...
}
...
]
```
--------------------------------
### Get fbp Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Retrieve the fbp (Facebook Page ID) parameter using the getFbp() method.
```javascript
const fbp = builder.getFbp();
```
--------------------------------
### Get fbc parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Retrieve the fbc (Facebook Click ID) parameter using the get_fbc() method.
```python
fbc = paramBuilder.get_fbc()
```
--------------------------------
### Get and Save Cookies using getCookiesToSet
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Optional method to retrieve the list of cookies to be saved using getCookiesToSet and then save them.
```javascript
for (const cookie of builder.getCookiesToSet()) {
responseCookies.push(cookie.name + '=' + cookie.value + '; Max-Age=' +
cookie.maxAge + '; Domain=' + cookie.domain + '; Path=/');
}
res.setHeader('Set-Cookie', responseCookies);
```
--------------------------------
### Construct Conversions API Payload with URLs
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Send extracted event_source_url and referrer_url with your Conversions API payload to enhance event matching and attribution quality. This example shows how to include these URLs along with user data.
```ruby
data = {
event_name: '...',
event_time: Time.now.to_i,
event_source_url: builder.get_event_source_url(),
referrer_url: builder.get_referrer_url(),
user_data: {
fbc: builder.get_fbc(),
fbp: builder.get_fbp(),
},
}
```
--------------------------------
### Get fbp from Cookie
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Retrieves the `fbp` value previously stored in a cookie. Ensure `processAndCollectAllParams` has been called first.
```javascript
const fbp = clientParamBuilder.getFbp();
```
--------------------------------
### Get fbp Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Retrieves the fbp (Facebook Pixel ID) parameter from the ParamBuilder instance after processing the request.
```java
String fbp = paramBuilder.getFbp();
```
--------------------------------
### Get Referrer URL
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Retrieve the referrer URL, which indicates the previous page the user visited before landing on the current page.
```php
$referrer_url = $param_builder->getReferrerUrl();
```
--------------------------------
### Get fbc from Cookie
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Retrieves the `fbc` value previously stored in a cookie. Ensure `processAndCollectAllParams` has been called first.
```javascript
const fbc = clientParamBuilder.getFbc();
```
--------------------------------
### Get Client IP Address
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Retrieve the client's IP address, which is a crucial piece of user data for the Conversions API.
```php
$client_ip_address = $param_builder->getClientIpAddress();
```
--------------------------------
### Get Event Source and Referrer URLs
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
After processing the request context, retrieve the extracted event source URL and referrer URL. These are crucial for improving event matching and attribution quality.
```php
$event_source_url = $param_builder->getEventSourceUrl();
$referrer_url = $param_builder->getReferrerUrl();
```
--------------------------------
### Get fbp Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Retrieve the fbp (Facebook Pixel ID) parameter, used for identifying users across sessions.
```php
$fbp = $param_builder->getFbp();
```
--------------------------------
### Run Local Demo Application
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Checkout and run the demo application to see the parameter builder in action. Visit http://localhost:3000/ to view the webpage.
```bash
node server.js
```
--------------------------------
### Build Demo Application
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Build the demo application using Gradle. This command compiles and packages the demo project.
```bash
./gradlew build
```
--------------------------------
### Get Client IP Address from Cookie
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Retrieves the `client_ip_address` value stored in a cookie. This requires `processAndCollectAllParams` to have been called with a valid `getIpFn`; otherwise, it returns an empty string.
```javascript
const ip = clientParamBuilder.getClientIpAddress();
```
--------------------------------
### Initialize ParamBuilder with empty input
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
This option is not recommended as it may lead to less accurate results by defaulting to a domain one level down from the input host.
```ruby
builder = ParamBuilder.new()
```
--------------------------------
### Initialize ParamBuilder with etld+1 list
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Recommended way to initialize ParamBuilder by providing a list of etld+1 domains.
```python
paramBuilder = ParamBuilder(["example.com"])
```
--------------------------------
### Get fbp
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Retrieve the Facebook Pixel ID (fbp) value managed by the ParamBuilder.
```ruby
fbp = builder.get_fbp()
```
--------------------------------
### Get fbc
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Retrieve the Facebook Click ID (fbc) value managed by the ParamBuilder.
```ruby
fbc = builder.get_fbc()
```
--------------------------------
### Java Test Command
Source: https://github.com/facebook/capi-param-builder/blob/main/AGENTS.md
Run this command to build the Java implementation and execute tests. Ensure the gradlew script is executable. Tested on Java versions 8, 11, 17, and 21.
```bash
cd java/capi-param-builder
chmod +x ./gradlew
./gradlew build
```
--------------------------------
### Process Request using Framework Context
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Recommended method to process request details like fbc, fbp, client_ip_address, event_source_url, and referrer_url. Pass your framework's request object directly.
```javascript
const cookiesToSet = builder.processRequestFromContext(req);
```
--------------------------------
### Initialize ParamBuilder with ETLD+1 Domains
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Recommended way to initialize ParamBuilder by providing a list of etld+1 domains. This helps in saving cookies.
```java
// Option 1 - Recommended: input list of etld+1 domains
ParamBuilder paramBuilder = new ParamBuilder(Arrays.asList('example.com', 'yourDomain.com'));
```
--------------------------------
### Include Bundle via Script Tag
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Alternatively, include the library directly in your HTML using a script tag pointing to the unpkg CDN.
```html
```
--------------------------------
### Initialize Param Builder with Domain List
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Use this option to initialize the ParamBuilder with a list of domains. The library will compare your current hostname and provide a recommended domain for saving cookies.
```php
$param_builder = new FacebookAds\ParamBuilder(array('example.com', 'test.com'));
```
--------------------------------
### Initialize ParamBuilder with Website Domains
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Recommended way to initialize ParamBuilder using a list of ETLD+1 for your website domains. This aids in suggesting cookie saving domains.
```javascript
const {ParamBuilder} = require('capi-param-builder');
// [Recommended] Option 1: List of ETLD+1 for your website domains.
// This helps provide suggestions for your cookie saving domain.
const builder = new ParamBuilder(["example.com", "localhost"]);
```
--------------------------------
### Initialize ParamBuilder with etld+1 list
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Use this option when you have a predefined list of etld+1 domains to match against the current hostname for cookie domain recommendations.
```ruby
builder = ParamBuilder.new(["localhost", "example.com"])
```
--------------------------------
### Get fbc Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Retrieve the fbc (Facebook Click ID) parameter using the getFbc() method.
```javascript
const fbc = builder.getFbc();
```
--------------------------------
### Process Request from Context with Slim/PSR-7 Server Params
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
For frameworks adhering to PSR-7, such as Slim, use the `$request->getServerParams()` method to provide the server parameters to the builder.
```php
$param_builder->processRequestFromContext($request->getServerParams());
```
--------------------------------
### Initialize ParamBuilder with Empty Input
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Not recommended: Initialize ParamBuilder with empty input. The SDK will attempt to guess your domain by looking one level down from the input host.
```javascript
// Option 3: Not recommended. Empty input.
// Not recommended. We will return a best guess on your domain by one level down your input host.
const builder = new ParamBuilder();
```
--------------------------------
### Build Project
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Builds the project for production or development environments using Yarn scripts.
```bash
yarn build # production build
yarn build:dev # development build
```
--------------------------------
### Initialize Param Builder (Default)
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Initialize the ParamBuilder without any arguments. This uses a less accurate, default method for subdomain resolution, which is not recommended for production environments.
```php
$param_builder = new FacebookAds\ParamBuilder();
```
--------------------------------
### Get fbc Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Retrieves the fbc (Facebook Click ID) parameter from the ParamBuilder instance after processing the request.
```java
String fbc = paramBuilder.getFbc();
```
--------------------------------
### Initialize ParamBuilder with custom resolver
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Implement a custom ETLD+1 resolver to provide specific logic for determining the etld+1 domain where cookies should be saved.
```ruby
# example implementation DefaultEtldPlusOneResolver from example/resolver. Feel free to provide your owne resolver.
builder = ParamBuilder.new(DefaultEtldPlusOneResolver.new())
```
--------------------------------
### Process Request from Context
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Recommended method to process request parameters like fbc, fbp, client_ip_address, event_source_url, and referrer_url. It reads data from superglobals if no context is provided.
```php
$cookie_to_set = $param_builder->processRequestFromContext(); // reads from $_SERVER
```
--------------------------------
### Process request context
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Use this method to process fbc, fbp, event_source_url, and referrer_url from the request object. Pass your framework's request object or Rack env hash directly.
```ruby
cookies_to_be_updated = builder.process_request_from_context(request)
```
--------------------------------
### Process request from context
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Recommended method to process requests by passing the framework's request object. The SDK extracts necessary information and returns cookies to set.
```python
updated_cookies = paramBuilder.process_request_from_context(request)
```
--------------------------------
### Process Request with Context
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Recommended method to process requests using the framework's request object. It extracts host, cookies, query, and referer to return updated cookies.
```java
List updatedCookieList = paramBuilder.processRequestFromContext(request);
```
--------------------------------
### Initialize ParamBuilder without input (Not Recommended)
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Initialize ParamBuilder without any input. This method is not recommended as it may miss accuracy by returning one level down from the input URL.
```python
paramBuilder = ParamBuilder() # Not recommended.
```
--------------------------------
### Initialize Param Builder with Custom Resolver
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Initialize the ParamBuilder with a custom ETLD+1 resolver by implementing the ETLDPlus1Resolver interface. This provides more control over domain resolution.
```php
$param_builder = new FacebookAds\ParamBuilder(new ETLDPlus1ResolverForTest());
```
--------------------------------
### Get fbc Parameter
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Retrieve the fbc (Facebook Click ID) parameter, which is used for tracking user interactions originating from Facebook ads.
```php
$fbc = $param_builder->getFbc();
```
--------------------------------
### Process Request from Context
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Use this method to automatically extract host, cookies, query, and referer from a Rack-based framework request object. It's recommended for extracting event_source_url and referrer_url.
```ruby
builder.process_request_from_context(request)
event_source_url = builder.get_event_source_url()
referrer_url = builder.get_referrer_url()
```
--------------------------------
### Process and Collect All Parameters
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Processes and collects `fbc` and `fbp` parameters, saving them into cookies. It also retrieves client IP addresses and backup click IDs from in-app browsers. The `getIpFn` is optional and should return the client's IPv6 address, falling back to IPv4.
```javascript
const params = await clientParamBuilder.processAndCollectAllParams(url, getIpFn);
```
--------------------------------
### Initialize ParamBuilder with Custom Resolver
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Initialize ParamBuilder using a custom ETLD+1 resolver for analysis and return.
```java
// Option 2: get your own etld+1 resolver to analysis and return your ETLD+1.
// ParamBuilder paramBuilder = new ParamBuilder(new YourETLDPlusOneResolver());
```
--------------------------------
### Python Test Command
Source: https://github.com/facebook/capi-param-builder/blob/main/AGENTS.md
Execute this command to run unit tests for the Python implementation. Tested on Python versions 3.9, 3.10, and 3.11.
```bash
cd python/capi_param_builder
python3 -m unittest test/test_param_builder.py
```
--------------------------------
### Process request (Deprecated)
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
This method is deprecated and does not construct event_source_url. Prefer `process_request_from_context`.
```ruby
cookies_to_be_updated = builder.process_request(
domain, # str: current host
name query_params, #dict[str, List[str]]: query params as hash type
cookie_dict,#dict[str, str]: current cookies as hash type
referral_link) #Optional[str]: optional current referer
```
--------------------------------
### Run Tests
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Executes all project tests or specific test files using Yarn. The `-- --testPathPattern` flag allows filtering tests.
```bash
yarn test # run all tests
yarn test -- --testPathPattern cookieUtil.test.js # run specific test file
```
--------------------------------
### Process Request with Hapi Framework
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
When using the Hapi framework, the raw request object needs to be explicitly passed to `processRequestFromContext` as `request.raw.req`.
```javascript
builder.processRequestFromContext(request.raw.req);
```
--------------------------------
### Process and Collect All Parameters with Custom IP Function
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/example/public/dev/index.html
This snippet shows how to use `processAndCollectAllParams` with a custom function to retrieve the client's IP address. It logs the collected parameters, fbc, fbp, client IP, and normalized PII. The result is also displayed on the page.
```javascript
let getIPfn = async function () {
return await (await fetch('https://api64.ipify.org')).text();
}
async function main() {
const processAndCollectAllParams = await clientParamBuilder.processAndCollectAllParams(null, getIPfn);
console.log(processAndCollectAllParams);
console.log('getFbc:' + clientParamBuilder.getFbc());
console.log('getFbp:' + clientParamBuilder.getFbp());
console.log('getClientIpAddress:' + clientParamBuilder.getClientIpAddress());
console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' John\_Smith@gmail.com ','email'));
console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' +001 (616) 954-78 88 ','phone'));
console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' 62a14e44f765419d10fea99367361a727c12365e2520f32218d505ed9aa0f62f ','email'));
console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' 62a14e44f765419d10fea99367361a727c12365e2520f32218d505ed9aa0f62f.AQYBAQAA ','email'));
document.getElementById('clientParamBuilder-lib').textContent = JSON.stringify(processAndCollectAllParams);
const appendix = [];
[...atob(clientParamBuilder.getFbc().split('.')[4])].map(c => appendix.push(c.charCodeAt(0)));
const version = `${appendix[3]}.${appendix[4]}.${appendix[5]}`;
document.getElementById('decoded-appendix').textContent = appendix;
document.getElementById('decoded-version').textContent = version;
}
main();
console.log('--------------Line----------------------');
console.log( 'You need to get user cookie consent first, below processAndCollectAllParams will set cookies.' );
console.log('return all params:processAndCollectAllParams');
```
--------------------------------
### Initialize ParamBuilder without Specific Resolver
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Initialize ParamBuilder without a specific resolver. This is not recommended as it may not accurately determine the cookie domain.
```java
// Option 3: not recommended. We'll return the cookie domain same as your current url(one level down). This may not accurate for your case.
// ParamBuilder paramBuilder = new ParamBuilder();
```
--------------------------------
### Construct Conversions API Payload
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Build a Conversions API payload by including extracted `event_source_url` and `referrer_url` along with user data parameters like `fbc` and `fbp`. These URLs enhance event matching and attribution quality.
```java
Map data = new HashMap<>();
data.put("event_name", "...");
data.put("event_time", System.currentTimeMillis() / 1000);
data.put("event_source_url", paramBuilder.getEventSourceUrl());
data.put("referrer_url", paramBuilder.getReferrerUrl());
Map userData = new HashMap<>();
userData.put("fbc", paramBuilder.getFbc());
userData.put("fbp", paramBuilder.getFbp());
data.put("user_data", userData);
```
--------------------------------
### Process Request from Context with Symfony/Laravel Server Bag
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
When using Symfony or Laravel, pass the framework's server bag to process the request. This ensures correct extraction of server parameters.
```php
$param_builder->processRequestFromContext($request->server->all());
```
--------------------------------
### Process Request from Context
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Use `processRequestFromContext` to automatically extract host, cookies, query, and referer from the request object. This method supports various framework request types and `null` for empty defaults. It is the recommended approach for extracting `eventSourceUrl` and `referrerUrl`.
```java
paramBuilder.processRequestFromContext(request);
String eventSourceUrl = paramBuilder.getEventSourceUrl();
String referrerUrl = paramBuilder.getReferrerUrl();
```
--------------------------------
### Process Request from Context Automatically
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
This method automatically reads from the `$_SERVER` superglobal to extract necessary request details like host, cookies, and query parameters.
```php
$param_builder->processRequestFromContext(); // reads from $_SERVER automatically
```
--------------------------------
### processAndCollectAllParams
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Processes and collects fbc and fbp parameters, saving them into cookies. It also retrieves client IP addresses and backup click IDs from in-app browsers. The function can optionally accept a URL and a function to retrieve the client's IP address.
```APIDOC
## processAndCollectAllParams(url, getIpFn)
### Description
Processes and collects `fbc` and `fbp` parameters (saving them into cookies), and also retrieves client IP addresses and backup click IDs from in-app browsers.
### Parameters
- `url` (string) - Optional. The URL to process.
- `getIpFn` (function) - Optional. A user-provided function to retrieve client IP addresses. It should return a string representing the client's IPv6 address, with a fallback to IPv4 if IPv6 is unavailable.
### Returns
An object containing `_fbc`, `_fbp`, and additional parameter values.
### Example
```javascript
const params = await clientParamBuilder.processAndCollectAllParams(url, getIpFn);
const getIpFn = async () => {
// Implementation to fetch client IP address (e.g., using an external API)
// Prefer IPv6, fallback to IPv4
return (await fetch('https://api64.ipify.org')).text();
};
await clientParamBuilder.processAndCollectAllParams(null, getIpFn);
```
```
--------------------------------
### Process Request with Referer URL
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Deprecated method to process requests including the referer URL. Prefer `processRequestFromContext`.
```java
// Option 1: with referer url
List updatedCookieList =
paramBuilder.processRequest(
request.getHeader("host"),
request.getParameterMap(),
cookieMap,
request.getHeader("referer"));
```
--------------------------------
### Set Cookies on Server
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Iterate through the cookies returned by the builder and set them on the server using the `setcookie` function. This ensures consistency for fbc and fbp across events.
```php
foreach ($cookie_to_set as $cookie) {
setcookie(
$cookie->name,
$cookie->value,
time() + $cookie->max_age,
'/',
$cookie->domain);
}
```
--------------------------------
### Save cookies from process_request_from_context
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Save the recommended cookies obtained from `process_request_from_context` to your web server's response. Ensure the `expires` parameter is set correctly for your framework.
```ruby
# Get the recommended saved cookie from step 4 above
cookies_to_be_updated = builder.process_request_from_context(request)
for cookie in cookies_to_be_updated do response.set_cookie(
cookie.name,
value: cookie.value,
domain: cookie.domain,
path: "/",
# for sinatra the expires is an absolute ts
# Check your web framework to have the correct expires.
expires: Time.now + cookie.max_age)
end
```
--------------------------------
### Extract Event Source and Referrer URLs with ParamBuilder
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Use paramBuilder.process_request_from_context to automatically extract event_source_url and referrer_url from the request. These are recommended for better event matching and attribution.
```python
paramBuilder.process_request_from_context(request)
event_source_url = paramBuilder.get_event_source_url()
referrer_url = paramBuilder.get_referrer_url()
```
--------------------------------
### Process Tornado Request with ParamBuilder
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
For frameworks like Tornado, manually construct an environ-style dictionary from the request object before passing it to paramBuilder.process_request_from_context.
```python
paramBuilder.process_request_from_context({
"HTTP_HOST": request.host,
"HTTP_REFERER": request.headers.get("Referer"),
"QUERY_STRING": request.query,
"HTTP_COOKIE": request.headers.get("Cookie", ""),
"REMOTE_ADDR": request.remote_ip,
})
```
--------------------------------
### Process request (Deprecated)
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Deprecated method for processing requests. It does not construct event_source_url. Prefer process_request_from_context.
```python
updated_cookies = paramBuilder.process_request(
domain, # str: current full domain url
query_params, #dict[str, List[str]]: query params
cookie_dict, # dict[str, str]: cookies dict
referral_link, #Optional[str]: optional string for full url with query params )
```
--------------------------------
### Extract Event Source and Referrer URLs
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Use `processRequestFromContext` to automatically extract `event_source_url` and `referrer_url` from the incoming request. These URLs improve event matching and attribution quality.
```javascript
builder.processRequestFromContext(req);
const eventSourceUrl = builder.getEventSourceUrl();
const referrerUrl = builder.getReferrerUrl();
```
--------------------------------
### Construct Conversions API Payload with URL Data
Source: https://github.com/facebook/capi-param-builder/blob/main/python/README.md
Include extracted event_source_url and referrer_url in your Conversions API payload to enhance event matching and attribution. Also includes fbc and fbp from user data.
```python
data = {
"event_name": "...",
"event_time": int(time.time()),
"event_source_url": paramBuilder.get_event_source_url(),
"referrer_url": paramBuilder.get_referrer_url(),
"user_data": {
"fbc": paramBuilder.get_fbc(),
"fbp": paramBuilder.get_fbp(),
},
}
```
--------------------------------
### Process and Collect All Parameters
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/example/public/index.html
This function collects various parameters including click IDs, IP addresses, and PII. It requires user cookie consent and allows for a custom IP collection function. The output is then displayed and set as the text content of an HTML element.
```javascript
My JS Library Test console.log( 'You need to get user cookie consent first, below processAndCollectAllParams will set cookies.' ); console.log('return all params:processAndCollectAllParams'); // getIPfn is a function to retrieve the client's IPv6 address, with a fallback to IPv4 if IPv6 is unavailable. // Please note that the implementation here is for demo purpose only, and you should implement your own logic to collect client IPv6 addresses. let getIPfn = async function () { return await (await fetch('https://api64.ipify.org')).text(); } async function main() { // @params url: [optional] string. The full URL you want to collect clickID from. // @params getIpFn: [optional] function. The function you implemented to collect client IPv6 addresses from. If IPv6 is not available for clients, you should fallback to IPv4. const processAndCollectAllParams = await clientParamBuilder.processAndCollectAllParams(null, getIPfn); console.log(processAndCollectAllParams); console.log('getFbc:' + clientParamBuilder.getFbc()); console.log('getFbp:' + clientParamBuilder.getFbp()); console.log('getClientIpAddress:' + clientParamBuilder.getClientIpAddress()); console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' John_Smith@gmail.com ','email')); console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' +001 (616) 954-78 88 ','phone')); console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' 62a14e44f765419d10fea99367361a727c12365e2520f32218d505ed9aa0f62f ','email')); console.log('getNormalizedAndHashedPII:' + clientParamBuilder.getNormalizedAndHashedPII(' 62a14e44f765419d10fea99367361a727c12365e2520f32218d505ed9aa0f62f.AQYBAQAA ','email')); document.getElementById('clientParamBuilder-lib').textContent = JSON.stringify(processAndCollectAllParams); } main(); console.log('--------------Line----------------------');
```
--------------------------------
### Lint and Format Code
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Runs linting and formatting checks on the codebase using Yarn scripts.
```bash
yarn lint
yarn format
```
--------------------------------
### Save cookies from get_cookies_to_set
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Save the recommended cookies obtained from `get_cookies_to_set` to your web server's response. Ensure the `expires` parameter is set correctly for your framework.
```ruby
# Get the recommended saved cookie from step 4 above
builder.process_request_from_context(request)
# `cookies_to_be_updated` from get_cookies_to_set()
for cookie in builder.get_cookies_to_set() do
response.set_cookie(
cookie.name,
value: cookie.value,
domain: cookie.domain,
path: "/",
# for sinatra the expire time, is an absolute ts
# Check your web framework to have the correct expires.
expires: Time.now + cookie.max_age)
end
```
--------------------------------
### Format data for Conversions API
Source: https://github.com/facebook/capi-param-builder/blob/main/ruby/README.md
Structure the collected event data, including user data (fbc, fbp) and event-level information (event_source_url, referrer_url), for sending to the Facebook Conversions API.
```ruby
data=[
'event_name': '...',
'event_time': ,
'event_source_url': event_source_url, # The value provided in step 6
'referrer_url': referrer_url, # The value provided in step 6
'user_data': {
'fbc': fbc, # The value provided in step 6
'fbp': fbp, # The value provided in step 6 ...
}
...
]
```
--------------------------------
### Send Parameters to Conversions API
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Structure and send the collected parameters to the Facebook Conversions API. User data includes normalized and hashed PII, while event data includes URLs and identifiers.
```json
data=[
'event_name': '...',
'event_time': ,
'event_source_url': $event_source_url, // The value provided in step 5
'referrer_url': $referrer_url, // The value provided in step 5
'user_data': {
'fbc': $fbc, // The value provided in step 5
'fbp': $fbp, // The value provided in step 5
'client_ip_address': $client_ip_address // The value provided in step 5
'em': $email // The value provided in step 5
'ph': $phone // The value provided in step 5
...
}
...
]
```
--------------------------------
### Deprecated Process Request
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Deprecated method for processing requests. It does not construct event_source_url. Prefer `processRequestFromContext`.
```php
$param_builder->processRequest(
$host_name, // string for full url
$url_query_params, // map for query params
$cookie, // map for cookies
$referral_link, // (optional, nullable)string, full referral link to help improve potential event quality.
$x_forwarded_for, // (optional, nullable)string, the http x_forwarded_for request header.
$remote_address // (optional, nullable)string, the remote_address variable in http request.
);
```
--------------------------------
### Send Conversions API Payload with URL Data
Source: https://github.com/facebook/capi-param-builder/blob/main/php/README.md
Include the extracted `event_source_url` and `referrer_url` in your Conversions API payload. This enhances event matching and attribution accuracy.
```php
$data = [
'event_name' => '...',
'event_time' => time(),
'event_source_url' => $param_builder->getEventSourceUrl(),
'referrer_url' => $param_builder->getReferrerUrl(),
'user_data' => [
'fbc' => $param_builder->getFbc(),
'fbp' => $param_builder->getFbp(),
'client_ip_address' => $param_builder->getClientIpAddress(),
],
];
```
--------------------------------
### Send URLs with Conversions API Payload
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Include the extracted `event_source_url` and `referrer_url` in your Conversions API payload to enhance event matching. Also includes other user data parameters.
```javascript
const data = {
event_name: '...',
event_time: Math.floor(Date.now() / 1000),
event_source_url: builder.getEventSourceUrl(),
referrer_url: builder.getReferrerUrl(),
user_data: {
fbc: builder.getFbc(),
fbp: builder.getFbp(),
client_ip_address: builder.getClientIpAddress(),
},
};
```
--------------------------------
### Process Request (Deprecated)
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Deprecated method for processing requests. It does not construct eventSourceUrl. Prefer processRequestFromContext.
```javascript
const cookiesToSet = builder.processRequest(
req.headers.host, // host
params, // query params
requestCookies, // current cookie
req.headers.referer, // optional, help enhance the accuracy
req.headers['x-forwarded-for'] ?? null, // optional, help select the best client_ip_address
req.socket.remoteAddress ?? null // optional, help select the best client_ip_address
);
```
--------------------------------
### Process Request without Referer URL
Source: https://github.com/facebook/capi-param-builder/blob/main/java/README.md
Deprecated method to process requests without the referer URL. Prefer `processRequestFromContext`.
```java
// Option 2: without referer url
List updatedCookieList =
paramBuilder.processRequest(
request.getHeader("host"),
request.getParameterMap(),
cookieMap);
```
--------------------------------
### Normalize and Hash Email PII
Source: https://github.com/facebook/capi-param-builder/blob/main/nodejs/README.md
Normalize and hash an email address using getNormalizedAndHashedPII with 'email' data type.
```javascript
const email = builder.getNormalizedAndHashedPII('John_Smith@gmail.com','email');
```
--------------------------------
### getClientIpAddress
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Retrieves the 'client_ip_address' value from the cookie. This method requires `processAndCollectAllParams` to be called with a valid `getIpFn` to populate the cookie; otherwise, it returns an empty string.
```APIDOC
## getClientIpAddress()
### Description
Returns the `client_ip_address` value from the cookie. This method relies on `processAndCollectAllParams` being called with a valid `getIpFn` to populate the cookie. If not, it returns an empty string.
### Returns
string - The client IP address stored in the cookie, or an empty string if not available.
### Example
```javascript
const ip = clientParamBuilder.getClientIpAddress();
```
```
--------------------------------
### getFbp
Source: https://github.com/facebook/capi-param-builder/blob/main/client_js/README.md
Retrieves the 'fbp' value from the cookie. This method should be called after `processAndCollectAllParams` has been executed.
```APIDOC
## getFbp()
### Description
Returns the `fbp` value from the cookie. Ensure `processAndCollectAllParams` has been called prior to using this method.
### Returns
string - The `fbp` value stored in the cookie.
### Example
```javascript
const fbp = clientParamBuilder.getFbp();
```
```