npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@agenus-io/pixel-backend-sdk

v1.0.26

Published

SDK para envio de vendas para fila AWS SQS do micro-serviço de pixels

Downloads

974

Readme

Pixel SDK

SDK completo para gerenciamento de pixels e envio de vendas para fila AWS SQS do micro-serviço de pixels (Meta/Facebook, Google, TikTok).

Instalação

npm install @agenus-io/pixel-backend-sdk
# ou
yarn add @agenus-io/pixel-backend-sdk
# ou
pnpm add @agenus-io/pixel-backend-sdk

Funcionalidades

Este SDK fornece duas funcionalidades principais:

  1. Gerenciamento de Pixels: CRUD completo de pixels (Create, Update, Delete, Get, GetOne)
  2. Envio de Vendas: Envio de pedidos/vendas para processamento via AWS SQS

Uso

Configuração Inicial

import { PixelSDK } from "@agenus-io/pixel-backend-sdk";
import type { AWSConfig, Order } from "@agenus-io/pixel-backend-sdk";

// Configure o SDK com suas credenciais AWS e credenciais da aplicação
const config: AWSConfig = {
  region: "us-east-1",
  accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  queueUrl: process.env.QUEUE_SALES_URL!,
};

const appId = process.env.APP_ID!;
const appToken = process.env.APP_TOKEN!;

const sdk = new PixelSDK(config, appId, appToken);

1. Enviar Vendas para a Fila

const order: Order = {
  dispatch: "META", // "META", "GOOGLE" ou "TIKTOK"
  event: "PURCHASE_COMPLETED", // ou "PURCHASE_PENDING"
  checkout: "cartpanda",
  orderId: "ORD-123456",
  subscriptionId: "SUB-789012", // opcional
  currency: "BRL",
  valueGross: 347.0,
  valueNet: 329.9,
  createdAt: new Date(),
  
  // Pixel IDs (opcional, dependendo da plataforma)
  fbc: "fb.1.1733718123.uYhGtFdSLoPqWeRtYuIo", // Meta/Facebook
  fbp: "fb.1.1733718123.4455667788", // Meta/Facebook
  fbclid: "fbclid-value", // Meta/Facebook
  gclid: "Cj0KCQi...", // Google
  gbraid: "gbraid-value", // Google
  wbraid: "wbraid-value", // Google
  
  customer: {
    email: "[email protected]",
    externalId: "USR-123", // opcional
    firstName: "João",
    lastName: "Silva",
    phone: "+55 11 99999-9999", // opcional
    city: "São Paulo", // opcional
    state: "SP", // opcional
    zipCode: "01310-100", // opcional
    country: "BR", // opcional
    ip: "189.45.201.77", // opcional
    userAgent: "Mozilla/5.0...", // opcional
  },
  
  products: [
    {
      id: "PROD-001",
      title: "Produto 1",
      externalId: "EXT-001",
      quantity: 2,
    },
    {
      id: "PROD-002",
      title: "Produto 2",
      externalId: "EXT-002",
      quantity: 1,
    },
  ],
};

try {
  await sdk.SendOrder({
    workspaceId: "workspace-123",
    order,
  });
  console.log("Venda enviada com sucesso!");
} catch (error) {
  console.error("Erro ao enviar venda:", error);
}

2. Gerenciar Pixels

Criar Pixel

await sdk.Create({
  workspaceId: "workspace-123",
  data: {
    title: "Pixel Meta",
    status: true,
    sendLead: true,
    sendLeadText: "Lead capturado",
    addToCart: true,
    addToCartText: "Produto adicionado ao carrinho",
    initiateCheckout: true,
    initiateCheckoutDetection: "AUTOMATIC",
    initiateCheckoutDetectionText: undefined,
    purchaseSendType: "SALES_APPROVED",
    purchaseValueType: "SALE_VALUE",
    type: "META",
    productIds: ["prod-1", "prod-2"],
    sendIp: "IPV6_AND_IPV4",
    pixelMeta: [
      {
        id: "pixel-id-123",
        title: "Pixel Principal",
        token: "pixel-token-123",
      },
    ],
  },
});

Listar Pixels

const result = await sdk.Get({
  workSpaceId: "workspace-123",
  page: 1,
  pageSize: 10,
  filter: undefined, // opcional
});

console.log(result.data); // Array de pixels
console.log(result.meta); // Metadados de paginação

Buscar um Pixel Específico

const result = await sdk.GetOne({
  id: "pixel-id-123",
  workSpaceId: "workspace-123",
});

console.log(result.data); // Dados do pixel ou null

Atualizar Pixel

await sdk.Update({
  id: "pixel-id-123",
  workspaceId: "workspace-123",
  data: {
    title: "Pixel Atualizado",
    status: false,
    // Apenas os campos que deseja atualizar
  },
});

Deletar Pixel

await sdk.Delete({
  id: "pixel-id-123",
  workspaceId: "workspace-123",
});

Tipos Exportados

MarketingPlatform

type MarketingPlatform = "GOOGLE" | "META" | "TIKTOK";

PurchaseEventType

type PurchaseEventType = "PURCHASE_PENDING" | "PURCHASE_COMPLETED";

PurchaseSendType

type PurchaseSendType = "SALES_APPROVED" | "SALES_APPROVED_AND_PENDING";

PurchaseValueType

type PurchaseValueType = "SALE_VALUE" | "COMMISSION";

InitiateCheckoutDetection

type InitiateCheckoutDetection = "AUTOMATIC" | "CONTAINS_TEXT" | "CONTAINS_CSS" | "CONTAINS_URL";

SendIp

type SendIp = "IPV6_AND_IPV4" | "ONLY_IPV6" | "DONT_SEND";

Order

Estrutura completa de dados da venda (veja exemplo acima).

AWSConfig

Configuração necessária para conexão com AWS SQS:

  • region: string - Região AWS
  • accessKeyId: string - Access Key ID
  • secretAccessKey: string - Secret Access Key
  • queueUrl: string - URL da fila SQS

SendSaleParams

Parâmetros para envio de venda:

  • workspaceId: string - ID do workspace
  • order: Order - Dados da venda/pedido

Variáveis de Ambiente

As credenciais AWS e da aplicação devem ser fornecidas ao instanciar o SDK. Recomendamos usar variáveis de ambiente:

AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=AKIA...
AWS_SECRET_ACCESS_KEY=secret...
QUEUE_SALES_URL=https://sqs.us-east-1.amazonaws.com/123456789012/queue-name
APP_ID=your-app-id
APP_TOKEN=your-app-token

Exemplo Completo

import { PixelSDK } from "@agenus-io/pixel-backend-sdk";
import type { AWSConfig, Order } from "@agenus-io/pixel-backend-sdk";

// 1. Configurar SDK
const config: AWSConfig = {
  region: process.env.AWS_REGION!,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  queueUrl: process.env.QUEUE_SALES_URL!,
};

const sdk = new PixelSDK(
  config,
  process.env.APP_ID!,
  process.env.APP_TOKEN!
);

// 2. Mapear venda do seu sistema para o formato do SDK
function mapOrderToSDKFormat(order: YourOrderType): Order {
  return {
    dispatch: order.platform, // "META", "GOOGLE", ou "TIKTOK"
    event: order.status === "completed" ? "PURCHASE_COMPLETED" : "PURCHASE_PENDING",
    checkout: order.checkoutProvider,
    orderId: order.id,
    currency: order.currency,
    valueGross: order.total,
    valueNet: order.subtotal,
    createdAt: order.createdAt,
    customer: {
      email: order.customer.email,
      firstName: order.customer.firstName,
      lastName: order.customer.lastName,
      phone: order.customer.phone,
      // ... outros campos opcionais
    },
    products: order.items.map(item => ({
      id: item.productId,
      title: item.title,
      externalId: item.externalId,
      quantity: item.quantity,
    })),
  };
}

// 3. Enviar venda
async function handleOrderCompleted(order: YourOrderType, workspaceId: string) {
  const orderData = mapOrderToSDKFormat(order);
  
  try {
    await sdk.SendOrder({
      workspaceId,
      order: orderData,
    });
    console.log(`Venda ${order.id} enviada com sucesso!`);
  } catch (error) {
    console.error(`Erro ao enviar venda ${order.id}:`, error);
    // Implemente sua lógica de retry ou notificação aqui
  }
}

// 4. Exemplo de uso completo com gerenciamento de pixels
async function exemploCompleto() {
  // Listar pixels
  const pixels = await sdk.Get({
    workSpaceId: "workspace-123",
    page: 1,
    pageSize: 10,
  });
  
  console.log(`Total de pixels: ${pixels.meta.total}`);
  
  // Enviar uma venda
  await handleOrderCompleted(myOrder, "workspace-123");
}

Manutenção

Quando houver atualizações no SDK:

  1. A versão será atualizada no npm
  2. Atualize o pacote nos seus apps: npm update @agenus-io/pixel-backend-sdk
  3. Se houver breaking changes, serão documentados nas release notes

Segurança

⚠️ IMPORTANTE: Nunca commite credenciais AWS ou tokens de aplicação no código fonte. Sempre use variáveis de ambiente ou serviços de gerenciamento de segredos (AWS Secrets Manager, etc).

API de Pixels

O SDK se conecta à API de pixels hospedada em: https://micro-service-pixel-production-4826.up.railway.app

Todas as operações CRUD de pixels utilizam autenticação via headers:

  • app-id: ID da aplicação
  • app-secret-token: Token secreto da aplicação
  • work-space-id: ID do workspace

Suporte

Para questões ou problemas, abra uma issue no repositório do projeto.