Inicio Home / SSJS / Artículo Article
SSJS 🟢 Beginner

Introducción a SSJS en SFMC

Introduction to SSJS in SFMC

SSJS (Server-Side JavaScript) en Salesforce Marketing Cloud te permite hacer peticiones HTTP a APIs externas directamente desde tus Cloud Pages o scripts de Automation Studio. Esta guía cubre los patrones más importantes: GET, POST, manejo de errores y autenticación.

📌 PREREQUISITO
Para ejecutar SSJS necesitas una Cloud Page o un Script Activity en Automation Studio. SSJS corre en el servidor de SFMC, no en el cliente.

01 · PETICIÓN HTTP GET

Usa HTTP.Get() para obtener datos de una API externa. Ideal para consumir endpoints que devuelven información sin necesidad de enviar body.

SSJS · Cloud Page
//  SSJS: HTTP GET Request 
var url = "https://api.example.com/users?active=true";

// Headers opcionales
var headerNames  = ["Authorization", "Content-Type"];
var headerValues = ["Bearer TOKEN_AQUI", "application/json"];

var response = HTTP.Get(url, headerNames, headerValues);

// response.StatusCode = 200, response.Content = JSON string
if (response.StatusCode == 200) {
  var data = Platform.Function.ParseJSON(response.Content);
  Write("Total usuarios: " + data.total);
} else {
  Write("Error: " + response.StatusCode);
}

02 · PETICIÓN HTTP POST

Usa HTTP.Post() cuando necesitas enviar datos a una API. El body debe ser un string (típicamente JSON serializado).

SSJS · Cloud Page
//  SSJS: HTTP POST Request 
var url = "https://api.example.com/contacts";

var payload = {
  firstName: "Juan",
  lastName:  "Pérez",
  email:     "[email protected]"
};

var body         = Stringify(payload);
var headerNames  = ["Authorization", "Content-Type"];
var headerValues = ["Bearer TOKEN_AQUI", "application/json"];
var statusCode   = [0]; // Array para recibir status

var response = HTTP.Post(url, "application/json", body, headerNames, headerValues, statusCode);

if (statusCode[0] == 201 || statusCode[0] == 200) {
  var result = Platform.Function.ParseJSON(response);
  Write("Contacto creado con ID: " + result.id);
} else {
  Write("Error " + statusCode[0] + ": " + response);
}
⚠️ IMPORTANTE
HTTP.Post() devuelve el body como string directamente, no un objeto. El status code se recibe en el array que pasas como último argumento.

03 · MANEJO DE ERRORES

Envuelve tus llamadas en try/catch para capturar errores de red o de parsing. Loguea los errores en una Data Extension para debugging.

SSJS · Manejo de Errores
try {
  var statusCode = [0];
  var response = HTTP.Post(url, "application/json", body,
                           headerNames, headerValues, statusCode);

  if (statusCode[0] >= 400) {
    throw "HTTP Error: " + statusCode[0] + " - " + response;
  }

  // Proceso exitoso...
  var data = Platform.Function.ParseJSON(response);

} catch(e) {
  // Loguear error en DE
  Platform.Function.InsertDE("ErrorLog",
    ["ErrorMsg", "Timestamp"],
    [e.message || Stringify(e), Now()]
  );
  Write("Algo salió mal. Por favor intenta más tarde.");
}

04 · AUTENTICACIÓN OAUTH2

Para llamar a la REST API de SFMC, primero necesitas obtener un token OAuth2. Este patrón es esencial para cualquier integración server-to-server.

SSJS · OAuth2 Token
//  Obtener Token OAuth2 de SFMC 
function getAccessToken(clientId, clientSecret, subdomain) {
  var authUrl = "https://" + subdomain + ".auth.marketingcloudapis.com/v2/token";

  var payload  = Stringify({
    grant_type:    "client_credentials",
    client_id:     clientId,
    client_secret: clientSecret
  });

  var statusCode = [0];
  var response = HTTP.Post(authUrl, "application/json",
                            payload, [], [], statusCode);

  if (statusCode[0] == 200) {
    var parsed = Platform.Function.ParseJSON(response);
    return parsed.access_token;
  }
  throw "Token error: " + statusCode[0];
}

// Uso:
var token    = getAccessToken("CLIENT_ID", "CLIENT_SECRET", "XXXX");
var apiUrl   = "https://XXXX.rest.marketingcloudapis.com/contacts/v1/contacts";
var headers  = ["Authorization", "Content-Type"];
var hValues  = ["Bearer " + token, "application/json"];
var sc       = [0];

var result = HTTP.Post(apiUrl, "application/json",
             Stringify({...}), headers, hValues, sc);
💡 PRO TIP
Guarda el access_token en una Data Extension con timestamp de expiración y reutilízalo durante su vida útil (1 hora) en lugar de generar uno nuevo en cada ejecución.

05 · CASOS DE USO REALES

✔️ CASO DE USO: Sincronizar leads desde HubSpot USE CASE: Sync leads from HubSpot

Con HTTP.Get() obtienes los deals recientes de HubSpot y los insertas en una DE de SFMC para usarlos en segmentaciones. Use HTTP.Get() to fetch recent HubSpot deals and insert them into an SFMC DE for segmentation.

✔️ CASO DE USO: Notificar webhooks al completar un Journey USE CASE: Notify webhooks when a Journey completes

Agrega un Script Activity al final del Journey con HTTP.Post() para notificar a tu CRM o sistema de tickets. Add a Script Activity at the end of the Journey using HTTP.Post() to notify your CRM or ticketing system.

06 · DESAFÍO ARCADE

🎮
MISIÓN: API Connector
MISSION: API Connector

Crea un Script Activity que consuma la API pública https://jsonplaceholder.typicode.com/users y guarde el nombre y email de cada usuario en una Data Extension llamada ExternalUsers.

Create a Script Activity that consumes the public API https://jsonplaceholder.typicode.com/users and saves each user's name and email in a Data Extension called ExternalUsers.

Ver solución View solution
Solución
var resp = HTTP.Get("https://jsonplaceholder.typicode.com/users", [], []);
if (resp.StatusCode == 200) {
  var users = Platform.Function.ParseJSON(resp.Content);
  for (var i = 0; i < users.length; i++) {
    Platform.Function.UpsertDE("ExternalUsers",
      ["Email"],
      ["Name", "Email"],
      [users[i].name, users[i].email]
    );
  }
}

SSJS (Server-Side JavaScript) in Salesforce Marketing Cloud lets you make HTTP requests to external APIs directly from your Cloud Pages or Automation Studio Script Activities. This guide covers the most important patterns: GET, POST, error handling, and OAuth2 authentication.

📌 PREREQUISITE
To run SSJS you need a Cloud Page or a Script Activity in Automation Studio. SSJS runs on the SFMC server, not on the client browser.

01 · HTTP GET REQUEST

Use HTTP.Get() to fetch data from an external API. Ideal for consuming endpoints that return information without needing to send a payload body.

SSJS · Cloud Page
//  SSJS: HTTP GET Request 
var url = "https://api.example.com/users?active=true";

var headerNames  = ["Authorization", "Content-Type"];
var headerValues = ["Bearer YOUR_TOKEN_HERE", "application/json"];

var response = HTTP.Get(url, headerNames, headerValues);

if (response.StatusCode == 200) {
  var data = Platform.Function.ParseJSON(response.Content);
  Write("Total users: " + data.total);
} else {
  Write("Error: " + response.StatusCode);
}

02 · HTTP POST REQUEST

Use HTTP.Post() when you need to send data to an API. The body must be a string (typically serialized JSON).

SSJS · Cloud Page
//  SSJS: HTTP POST Request 
var url = "https://api.example.com/contacts";

var payload = {
  firstName: "John",
  lastName:  "Doe",
  email:     "john.doe@example.com"
};

var body         = Stringify(payload);
var headerNames  = ["Authorization", "Content-Type"];
var headerValues = ["Bearer YOUR_TOKEN_HERE", "application/json"];
var statusCode   = [0];

var response = HTTP.Post(url, "application/json", body, headerNames, headerValues, statusCode);

if (statusCode[0] == 201 || statusCode[0] == 200) {
  var result = Platform.Function.ParseJSON(response);
  Write("Contact created with ID: " + result.id);
} else {
  Write("Error " + statusCode[0] + ": " + response);
}
⚠️ IMPORTANT
HTTP.Post() returns the body as a string directly. The status code is returned inside the array passed as the last parameter.

03 · ERROR HANDLING

Wrap your API calls in try/catch blocks to catch network or parsing errors. Log errors into a Data Extension for troubleshooting.

SSJS · Error Handling
try {
  var statusCode = [0];
  var response = HTTP.Post(url, "application/json", body,
                           headerNames, headerValues, statusCode);

  if (statusCode[0] >= 400) {
    throw "HTTP Error: " + statusCode[0] + " - " + response;
  }

  var data = Platform.Function.ParseJSON(response);

} catch(e) {
  Platform.Function.InsertDE("ErrorLog",
    ["ErrorMsg", "Timestamp"],
    [e.message || Stringify(e), Now()]
  );
  Write("Something went wrong. Please try again later.");
}

04 · OAUTH2 AUTHENTICATION

To call SFMC's REST API, you must first obtain an OAuth2 token. This pattern is essential for any server-to-server integration.

SSJS · OAuth2 Token
//  Obtain SFMC OAuth2 Token 
function getAccessToken(clientId, clientSecret, subdomain) {
  var authUrl = "https://" + subdomain + ".auth.marketingcloudapis.com/v2/token";

  var payload  = Stringify({
    grant_type:    "client_credentials",
    client_id:     clientId,
    client_secret: clientSecret
  });

  var statusCode = [0];
  var response = HTTP.Post(authUrl, "application/json",
                            payload, [], [], statusCode);

  if (statusCode[0] == 200) {
    var parsed = Platform.Function.ParseJSON(response);
    return parsed.access_token;
  }
  throw "Token error: " + statusCode[0];
}

// Usage:
var token    = getAccessToken("CLIENT_ID", "CLIENT_SECRET", "XXXX");
var apiUrl   = "https://XXXX.rest.marketingcloudapis.com/contacts/v1/contacts";
var headers  = ["Authorization", "Content-Type"];
var hValues  = ["Bearer " + token, "application/json"];
var sc       = [0];

var result = HTTP.Post(apiUrl, "application/json",
             Stringify({...}), headers, hValues, sc);
💡 PRO TIP
Cache your access_token in a Data Extension with an expiry timestamp and reuse it during its lifetime (1 hour) instead of generating a new one on every execution.

05 · REAL USE CASES

✔️ USE CASE: Sync leads from HubSpot

Use HTTP.Get() to fetch recent HubSpot deals and insert them into an SFMC DE for segmentation.

✔️ USE CASE: Notify webhooks when a Journey completes

Add a Script Activity at the end of the Journey using HTTP.Post() to notify your CRM or ticketing system.

06 · ARCADE CHALLENGE

🎮
MISSION: API Connector

Create a Script Activity that consumes the public API https://jsonplaceholder.typicode.com/users and saves each user's name and email in a Data Extension called ExternalUsers.

View solution
Solution
var resp = HTTP.Get("https://jsonplaceholder.typicode.com/users", [], []);
if (resp.StatusCode == 200) {
  var users = Platform.Function.ParseJSON(resp.Content);
  for (var i = 0; i < users.length; i++) {
    Platform.Function.UpsertDE("ExternalUsers",
      ["Email"],
      ["Name", "Email"],
      [users[i].name, users[i].email]
    );
  }
}
◀ Anterior
◀ Previous
Volver al catálogo
Back to catalog
ESC
ARTÍCULOS RECIENTES
🕹️ ¡CÓDIGO KONAMI! +9999 XP DESBLOQUEADOS