Docs

JavaScript Agent

Integration of Ambriel's JavaScript Agent into your web applications

Integrate our JavaScript Agent

The Ambriel JavaScript Agent is a lightweight library that allows you to easily integrate Ambriel's features into your web applications. It provides a simple API to track user interactions, manage sessions, and send data to the Ambriel platform.

Example tracking script:

<script>
    (function(w, d, s, u, n) {
        w[n] = w[n] || function() {
            (w[n].q = w[n].q || []).push(arguments);
        };
        w[n].ready = new Promise(res => w[n]._r = res);

        var js = d.createElement(s);
        js.async = true;
        js.src = u;
        d.head.appendChild(js);
    })(window, document, 'script', 'https://ambriel.io/agent/ambriel.js', 'ambriel');

    ambriel('create');
    ambriel.ready.then(async ambriel => {
        //get session
        const session = await ambriel.getSession();
    });
</script>

Installation

To install the Ambriel JavaScript Agent, you can include it directly in your HTML file using a <script> tag. Here's how to do it:

Add tracking script to your website

Add the following script tag to your HTML file, preferably before the closing </head> tag:

<script>
    (function(w, d, s, u, n) {
        w[n] = w[n] || function() {
            (w[n].q = w[n].q || []).push(arguments);
        };
        w[n].ready = new Promise(res => w[n]._r = res);

        var js = d.createElement(s);
        js.async = true;
        js.src = u;
        d.head.appendChild(js);
    })(window, document, 'script', 'https://ambriel.io/agent/ambriel.js', 'ambriel');

    ambriel('create');

    ambriel.ready.then(async ambriel => {
        const session = await ambriel.getSession();
        console.log('Ambriel session:', session);
        //{"id":"1i3h348sCCsjan3249590sHHWAb"}

        // Example: Save session ID to your backend
        fetch('/save-ambriel-session', { 
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ambriel_session: session.id })
        });
    });
</script>

Add session ID to your transaction payload

When processing a transaction, include the sessionId obtained from the JavaScript Agent in your transaction payload. Here's an example of how to do this in various programming languages:

# Example: Save the ambriel_session when the session is created
from flask import Flask, request, session, jsonify

@app.route('/save-ambriel-session', methods=['POST'])
def save_ambriel_session():  
    data = request.json
    ambriel_session = data['ambriel_session']

    # Save the ambriel_session to python session
    session['ambriel_session'] = ambriel_session
# Example: Save the ambriel_session when the session is created
import { Request, Response } from 'express';
import axios from 'axios';

app.post('/save-ambriel-session', saveAmbrielSession);

// Example: Save the ambriel_session when the session is created
export function saveAmbrielSession(req: Request) {  
    const ambrielSessionId = request.ambriel_session.id;
    // Save the ambrielSessionId to the user's session
    req.session.ambriel_session = ambrielSessionId;
}

// Example: Save the ambriel_session when the session is created

#[route('/save-ambriel-session', methods=['POST'])]
function saveAmbrielSession(Request $request) {  
    // Start the session if not already started
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    $ambrielSessionId = $request->get('ambriel_session');
    // Save the ambrielSessionId to the user's session
    $_SESSION['ambriel_session'] = $ambrielSessionId;
}
# Example: Save the ambriel_session when the session is created
package main

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "fmt"
)

// Example: Save the ambriel_session when the session is created
func SaveAmbrielSession(session map[string]interface{}, ambrielSession map[string]interface{}) { 
    ambrielSessionId, ok := ambrielSession["id"].(string)
    if !ok {
        // handle error
        return
    }
    // Save the ambrielSessionId to the user's session
    session["ambriel_session"] = ambrielSessionId
}

Send session to Ambriel Api

After getting the session ID from the JavaScript Agent and saving it to your backend, you can include it in your transaction payload when processing a transaction. Here's an example of how to do this in various programming languages:

# Example: Save the ambriel_session when the session is created
from flask import Flask

# Example: Then Process a transaction when an order is completed
def process_ambriel_tx(order):
    ambriel_session = session['ambriel_session']

    url = "https://api.ambriel.io/v1/transactions/"
    body = {
      "actionType": "purchase",
      "transactionId": "Test123123",
      "transactionType": "order",
      "transactionAmount": 1000.33,
      "transactionCurrency": "USD",
      "customer": {
        "id": "12345",
        "name": "John Doe",
        "firstName": "John",
        "lastName": "Doe"
      },
      "session": ambriel_session  
      # ... rest of the code
    }
    response = s.request("POST", url, json = body, headers = {
      "x-api-key": "string",
      "Content-Type": "application/json"
    })
import { Request, Response } from 'express';
import axios from 'axios';

// Example: Then Process a transaction when an order is completed
export async function processAmbrielTx(req: Request, order: any) {
    const ambrielSessionId = req.session.ambriel_session;

    const url = "https://api.ambriel.io/v1/transactions/";
    const body = {
      actionType: "purchase",
      transactionId: "Test123123",
      transactionType: "order",
      transactionAmount: 1000.33,
      transactionCurrency: "USD",
      customer: {
        id: "12345",
        name: "John Doe",
        firstName: "John",
        lastName: "Doe"
      },
      session: ambrielSessionId  
      // ... rest of the code
    };
    const response = await axios.post(url, body, {
      headers: {
        "x-api-key": "string",
        "Content-Type": "application/json"
      }
    });
    return response.data;
}

// Example: Then Process a transaction when an order is completed
function processAmbrielTx($order) {
    // Start the session if not already started
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    $ambrielSessionId = $_SESSION['ambriel_session'];

    $url = "https://api.ambriel.io/v1/transactions/";
    $body = [
      "actionType" => "purchase",
      "transactionId" => "Test123123",
      "transactionType" => "order",
      "transactionAmount" => 1000.33,
      "transactionCurrency" => "USD",
      "customer" => [
        "id" => "12345",
        "name" => "John Doe",
        "firstName" => "John",
        "lastName" => "Doe"
      ],
      "session" => $ambrielSessionId  
      // ... rest of the code
    ];

    $headers = [
      "x-api-key: string",
      "Content-Type: application/json"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if ($response === false) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }
    curl_close($ch);

    return json_decode($response, true);
}
package main

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "fmt"
)

// Example: Then Process a transaction when an order is completed
func ProcessAmbrielTx(session map[string]interface{}, order map[string]interface{}) (map[string]interface{}, error) {
    ambrielSessionId, ok := session["ambriel_session"].(string)
    if !ok {
        return nil, fmt.Errorf("ambriel_session not found in session")
    }

    url := "https://api.ambriel.io/v1/transactions/"
    body := map[string]interface{}{
        "actionType":         "purchase",
        "transactionId":      "Test123123",
        "transactionType":    "order",
        "transactionAmount":  1000.33,
        "transactionCurrency": "USD",
        "customer": map[string]interface{}{
            "id":        "12345",
            "name":      "John Doe",
            "firstName": "John",
            "lastName":  "Doe",
        },
        "session": ambrielSessionId, 
        // ... rest of the code
    }

    jsonBody, err := json.Marshal(body)
    if err != nil {
        return nil, err
    }

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
    if err != nil {
        return nil, err
    }
    req.Header.Set("x-api-key", "string")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    var result map[string]interface{}
    if err := json.Unmarshal(respBody, &result); err != nil {
        return nil, err
    }

    return result, nil
}