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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@davidpimentabenony/pixel-sdk

v1.0.18

Published

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

Readme

Pixel SDK

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

Instalação

npm install @pixel-microservice/sdk
# ou
yarn add @pixel-microservice/sdk
# ou
pnpm add @pixel-microservice/sdk

Uso

Método 1: Usando a classe PixelSDK (Recomendado para múltiplas vendas)

import { PixelSDK } from "@pixel-microservice/sdk";
import type { SaleData, AWSConfig } from "@pixel-microservice/sdk";

// Configure o SDK com suas credenciais AWS
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 sdk = new PixelSDK(config);

// Prepare os dados da venda
const sale: SaleData = {
  workspaceId: "workspace-123",
  app: {
    id: "app-id-123",
    token: "app-token-123",
  },
  order: {
    dispatch: "FACEBOOK", // ou "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().toISOString(),
    
    // Pixel IDs (opcional, dependendo da plataforma)
    fbc: "fb.1.1733718123.uYhGtFdSLoPqWeRtYuIo", // Facebook
    fbp: "fb.1.1733718123.4455667788", // Facebook
    gclid: "Cj0KCQi...", // Google
    
    customer: {
      email: "[email protected]",
      externalId: "USR-123",
      firstName: "João",
      lastName: "Silva",
      phone: "+55 11 99999-9999",
      city: "São Paulo",
      state: "SP",
      zipCode: "01310-100",
      country: "BR",
      ip: {
        content: "189.45.201.77",
        type: "IPV4",
      },
      userAgent: "Mozilla/5.0...",
    },
    
    products: [
      {
        id: "PROD-001",
        externalId: "EXT-001",
        quantity: 2,
      },
      {
        id: "PROD-002",
        externalId: "EXT-002",
        quantity: 1,
      },
    ],
  },
};

// Envie a venda
try {
  await sdk.sendSale({ sale });
  console.log("Venda enviada com sucesso!");
} catch (error) {
  console.error("Erro ao enviar venda:", error);
}

// Para enviar múltiplas vendas
await sdk.sendSales([sale1, sale2, sale3]);

Método 2: Usando função helper (Para uso simples)

import { sendSaleToQueue } from "@pixel-microservice/sdk";
import type { SaleData, AWSConfig } from "@pixel-microservice/sdk";

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 sale: SaleData = {
  // ... dados da venda
};

await sendSaleToQueue(config, sale);

Tipos Exportados

MarketingPlatform

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

PurchaseEventType

type PurchaseEventType = "PURCHASE_PENDING" | "PURCHASE_COMPLETED";

SaleData

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

Variáveis de Ambiente

As credenciais AWS devem ser fornecidas ao instanciar o SDK. Recomendamos usar variáveis de ambiente no seu aplicativo:

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

Exemplo Completo

import { PixelSDK } from "@pixel-microservice/sdk";
import type { SaleData, AWSConfig } from "@pixel-microservice/sdk";

// 1. Configurar SDK
const sdk = new PixelSDK({
  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!,
});

// 2. Mapear venda do seu sistema para o formato do SDK
function mapSaleToSDKFormat(order: YourOrderType): SaleData {
  return {
    workspaceId: order.workspaceId,
    app: {
      id: order.appId,
      token: order.appToken,
    },
    order: {
      dispatch: order.platform, // "FACEBOOK", "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.toISOString(),
      customer: {
        email: order.customer.email,
        firstName: order.customer.firstName,
        lastName: order.customer.lastName,
        phone: order.customer.phone,
        // ... outros campos
      },
      products: order.items.map(item => ({
        id: item.productId,
        externalId: item.externalId,
        quantity: item.quantity,
      })),
    },
  };
}

// 3. Enviar venda
async function handleOrderCompleted(order: YourOrderType) {
  const sale = mapSaleToSDKFormat(order);
  
  try {
    await sdk.sendSale({ sale });
    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
  }
}

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 @pixel-microservice/sdk
  3. Se houver breaking changes, serão documentados nas release notes

Segurança

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

Suporte

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