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

@refigure/magalu-api

v1.1.0

Published

[![npm](https://img.shields.io/npm/v/%40refigure%2Fmagalu-api.svg)](https://www.npmjs.com/package/@refigure/magalu-api) [![npm downloads](https://img.shields.io/npm/dm/%40refigure%2Fmagalu-api.svg)](https://www.npmjs.com/package/@refigure/magalu-api) [![l

Readme

Magalu API (TypeScript/JavaScript SDK)

npm npm downloads license Node.js Bun wakatime

Uma SDK minimalista e tipada para consumir a API de Seller da Magazine Luiza (Magalu) usando Fetch nativo, com arquitetura em POO, recursos organizados por domínio (orders, deliveries) e tipagens prontas para TypeScript.

Créditos: desenvolvido por Kelvin Kauan Melo Mattos.
MIT License © 2026 Kelvin Mattos


✨ O que essa lib entrega

  • POO: um client principal (MagaluAPI) com recursos separados por domínio
  • Fetch nativo (sem axios): funciona muito bem com Bun e Node
  • Tipagens completas para respostas e parâmetros (TypeScript)
  • Endpoints prontos
    • orders.getPedidoByOrder(orderId)
    • orders.getListPedidos(query)
    • deliveries.getDeliveryByLabel(labelId, limit?, offset?)
  • ✅ Tratamento básico de erro: lança Error com status HTTP + payload de erro (texto)

📦 Instalação

Bun

bun add @refigure/magalu-api

Node (npm / pnpm / yarn)

npm i @refigure/magalu-api
# ou
pnpm add @refigure/magalu-api
# ou
yarn add @refigure/magalu-api

Obs.: a lib é publicada como ESM ("type": "module").
Se você usa CommonJS, veja a seção CommonJS (require).


✅ Requisitos

  • Bun: qualquer versão moderna
  • Node.js: recomendado Node 18+ (por causa do fetch global)
  • TypeScript: (opcional) recomendado TS 5+

🚀 Quickstart (TypeScript)

import { MagaluAPI } from "@refigure/magalu-api";

const magalu = new MagaluAPI({
  baseUrl: "https://api.magalu.com",
  accessToken: process.env.MAGALU_ACCESS_TOKEN as string,
});

const pedidos = await magalu.orders.getListPedidos({
  _limit: 20,
  _offset: 0,
  _sort: "purchased_at:desc",
});

console.log("Qtd pedidos:", pedidos.results.length);
console.log("Primeiro pedido:", pedidos.results[0]);

🚀 Quickstart (JavaScript)

Node ESM ("type": "module")

import { MagaluAPI } from "@refigure/magalu-api";

const magalu = new MagaluAPI({
  baseUrl: "https://api.magalu.com",
  accessToken: process.env.MAGALU_ACCESS_TOKEN,
});

const pedidos = await magalu.orders.getListPedidos({
  _limit: 20,
  _sort: "purchased_at:desc",
});

console.log(pedidos.results.length);

CommonJS (require)

Como o pacote é ESM, use import dinâmico:

const { MagaluAPI } = await import("@refigure/magalu-api");

const magalu = new MagaluAPI({
  baseUrl: "https://api.magalu.com",
  accessToken: process.env.MAGALU_ACCESS_TOKEN,
});

⚙️ Configuração (MagaluConfig)

A lib precisa de:

  • baseUrl: base da API
  • accessToken: Bearer token do Seller Magalu

Exemplo:

import type { MagaluConfig } from "@refigure/magalu-api";

const config: MagaluConfig = {
  baseUrl: "https://api.magalu.com",
  accessToken: "SEU_TOKEN_AQUI",
};

Base URLs suportadas

export type MagaluBaseUrl =
  | "https://api.magalu.com"
  | "https://api-sandbox.magalu.com"
  | "https://services.magalu.com";

✅ Produção: https://api.magalu.com
🧪 Sandbox: https://api-sandbox.magalu.com
🔧 Serviços extras: https://services.magalu.com


📚 Recursos disponíveis

A lib expõe uma instância principal com os módulos:

const api = new MagaluAPI({ baseUrl, accessToken });

api.orders;      // OrdersResource
api.deliveries;  // DeliveriesResource

🧾 Orders (Pedidos)

1) Listar pedidos (getListPedidos)

const pedidos = await api.orders.getListPedidos({
  status: "approved",
  _limit: 50,
  _offset: 0,
  _sort: "purchased_at:desc",
});

console.log(pedidos.meta.page);
console.log(pedidos.results);

Parâmetros suportados

type GetListPedidosQueryParameters = {
  status?: "new" | "approved" | "cancelled" | "finished";
  purchased_at__gte?: string; // ISO 8601
  purchased_at__lte?: string; // ISO 8601
  updated_at__gte?: string;   // ISO 8601
  updated_at__lte?: string;   // ISO 8601
  code?: string;
  _offset?: number;
  _limit?: number;
  _sort?: "purchased_at:asc" | "purchased_at:desc";
};

Paginação

Use _offset e _limit. A API retorna:

pedidos.meta.page.count;
pedidos.meta.page.limit;
pedidos.meta.page.offset;
pedidos.meta.links.next; // query da próxima página

2) Buscar pedido por ID (getPedidoByOrder)

const pedido = await api.orders.getPedidoByOrder("ORDER_ID_AQUI");

console.log(pedido.code);
console.log(pedido.customer.name);
console.log(pedido.deliveries);

📦 Deliveries (Entregas)

1) Buscar entrega pela etiqueta (getDeliveryByLabel)

Esse endpoint consulta entregas filtrando pelo código de etiqueta (tag_code).

const delivery = await api.deliveries.getDeliveryByLabel("ETIQUETA_AQUI", 1, 0);

console.log(delivery.results.length);
console.log(delivery.results[0]);

Assinatura

getDeliveryByLabel(labelId: string, limit = 1, offset = 0)

Ele monta a query:

/seller/v1/deliveries?_limit={limit}&_offset={offset}&tag_code={labelId}

🧠 Tipagens (TypeScript)

Além do MagaluAPI, a lib exporta os principais tipos:

import type {
  GetListPedidosResponse,
  GetListPedidosQueryParameters,
  MagaluAPIGetPedidoResponse,
  GetDeliveryByLabelResponse,
  MagaluDeliveryStatus,
  MagaluSeller,
} from "@refigure/magalu-api";

❗ Tratamento de erros

A lib usa fetch() e, se o status não for 2xx, ela lança um Error:

  • inclui o método
  • inclui a URL final
  • inclui status HTTP
  • inclui o corpo de erro (texto), quando disponível

Exemplo recomendado:

try {
  const pedidos = await api.orders.getListPedidos({ _limit: 20 });
  console.log(pedidos.results.length);
} catch (err) {
  console.error("Falha ao consultar Magalu:", err);
}

💰 Sobre valores e normalizer

Em vários pontos da API (ex.: pagamentos), a Magalu trabalha com:

  • normalizer (geralmente 100)
  • amount/total em número inteiro

Exemplo:

  • amount: 2698
  • normalizer: 100
  • valor real: 2698 / 100 = 26.98 (R$ 26,98)

🔐 Segurança do accessToken

  • Nunca commite accessToken no repositório
  • Use .env / secrets do deploy (GitHub Actions, Railway, Render, etc.)
  • Em produção, injete via process.env

Exemplo:

MAGALU_ACCESS_TOKEN="..."

🧩 Exemplos de uso (mesma ideia do src/examples/basic.ts)

A ideia é:

  1. buscar pedidos
  2. pegar o primeiro
  3. pegar a primeira entrega
  4. pegar o primeiro item
const list = await api.orders.getListPedidos({
  _limit: 100,
  _offset: 0,
  _sort: "purchased_at:desc",
});

const first = list.results[0];
const firstDelivery = first?.deliveries?.[0];
const firstItem = firstDelivery?.items?.[0];

if (firstItem) {
  console.log("Produto:", firstItem.info.name);
}

🧪 Funciona com Bun?

Sim ✅

Bun já tem fetch() nativo e roda ESM muito bem:

bun run index.ts

🛠️ Roadmap (ideias)

A base está pronta para evoluir fácil:

  • [ ] retries com backoff
  • [ ] interceptors (log / trace)
  • [ ] endpoints de logística adicionais
  • [ ] suporte a POST/PUT/PATCH específicos da API

📄 Licença

MIT License © 2026 Kelvin Mattos


👤 Autor

Kelvin Kauan Melo Mattos
Feito com foco em automação e integração de marketplaces usando TypeScript + Bun.