Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,9 +430,9 @@ Used when loading via `widget-bootstrap.v1.min.js`:

```typescript
window.PaymentWidget.init(config: WidgetConfig): Promise<void>
window.PaymentWidget.open(merchantId?: string): void
window.PaymentWidget.close(merchantId?: string): void
window.PaymentWidget.destroy(merchantId?: string): void
window.PaymentWidget.open(orderId?: string): void
window.PaymentWidget.close(orderId?: string): void
window.PaymentWidget.destroy(orderId?: string): void
window.PaymentWidget.getState(): { isLoaded: boolean }
```

Expand Down Expand Up @@ -489,22 +489,22 @@ Always test via HTTP server (not `file://`) due to CORS restrictions.

### Issue: "ERR_NAME_NOT_RESOLVED" on widget load

**Cause**: Bootstrap has wrong CDN_BASE_URL
**Cause**: Bootstrap has wrong CDN_BASE_URL
**Solution**: Update `src/bootstrap/index.ts` with correct CloudFront URL, rebuild, and redeploy

### Issue: CORS errors in browser

**Cause**: S3 bucket missing CORS configuration
**Cause**: S3 bucket missing CORS configuration
**Solution**: Run `./deploy.sh` which configures CORS automatically, or manually apply CORS config

### Issue: Old files served after deploy

**Cause**: CloudFront cache not invalidated
**Cause**: CloudFront cache not invalidated
**Solution**: Script invalidates automatically. If manual: `aws cloudfront create-invalidation --distribution-id EOLJNTE5PW5O9 --paths "/*"`

### Issue: Widget not found in window object

**Cause**: Using wrong API for the loaded script
**Cause**: Using wrong API for the loaded script
**Solution**:

- Bootstrap loader → `window.PaymentWidget`
Expand Down
2 changes: 1 addition & 1 deletion PUBLISHING.md
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ CSS: https://d2x7cg3k3on9lk.cloudfront.net/widget.v1.min.css (4.6KB)
></script>
<script>
window.PaymentWidgetInit = {
merchantId: "merchant-123",
orderId: "merchant-123",
primaryColor: "#FF6600",
onSuccess: (data) => console.log("Sucesso:", data.token),
};
Expand Down
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Ou usando configuração via JavaScript:
></script>
<script>
window.PaymentWidgetInit = {
merchantId: "seu-merchant-123",
orderId: "seu-merchant-123",
primaryColor: "#FF6600",
logoUrl: "https://seusite.com/logo.png",
apiBaseUrl: "https://api.cartaosimples.com",
Expand Down Expand Up @@ -71,7 +71,7 @@ function App() {
return (
<PaymentWidget
config={{
merchantId: "seu-merchant-123",
orderId: "seu-merchant-123",
primaryColor: "#FF6600",
onSuccess: (data) => console.log("Sucesso:", data),
onError: (error) => console.error("Erro:", error),
Expand All @@ -87,7 +87,7 @@ function App() {
import { mount } from "cartao-simples-widget";

const widget = mount(document.getElementById("widget-container"), {
merchantId: "seu-merchant-123",
orderId: "seu-merchant-123",
primaryColor: "#FF6600",
onSuccess: (data) => console.log("Sucesso:", data),
});
Expand All @@ -102,7 +102,7 @@ widget.close();
```javascript
// Via CDN
window.PaymentWidget.init({
merchantId: "merchant-123",
orderId: "merchant-123",
autoOpen: false,
});

Expand All @@ -117,7 +117,7 @@ window.PaymentWidget.destroy();

| Propriedade | Tipo | Padrão | Descrição |
| ---------------- | --------- | --------- | -------------------------------------- |
| `merchantId` | `string` | - | **Obrigatório** - ID único do parceiro |
| `orderId` | `string` | - | **Obrigatório** - ID único do parceiro |
| `primaryColor` | `string` | `#ff6600` | Cor primária (hex) |
| `secondaryColor` | `string` | `#0a0a0a` | Cor secundária (hex) |
| `logoUrl` | `string` | - | URL do logo do parceiro |
Expand All @@ -143,7 +143,7 @@ window.PaymentWidget.destroy();
{
transactionId: "txn_123456789",
token: "tok_abcdef123",
merchantId: "merchant_001",
orderId: "merchant_001",
amount?: 1500.00,
installments?: 12,
timestamp: "2024-01-15T10:30:00Z"
Expand Down Expand Up @@ -291,7 +291,7 @@ https://cdn.cartaosimples.com/widget.v1.min.js (122KB)
<script>
document.getElementById("payment-btn").addEventListener("click", () => {
window.PaymentWidget.init({
merchantId: "loja-123",
orderId: "loja-123",
primaryColor: "#FF6600",
onSuccess: (data) => {
// Redirecionar para página de sucesso
Expand Down Expand Up @@ -336,7 +336,7 @@ export default function CheckoutPage() {

<PaymentWidget
config={{
merchantId: process.env.NEXT_PUBLIC_MERCHANT_ID!,
orderId: process.env.NEXT_PUBLIC_MERCHANT_ID!,
primaryColor: "#FF6600",
onSuccess: (data) => {
// Processar pagamento
Expand Down Expand Up @@ -397,7 +397,7 @@ O script `setup-cloudfront.sh` automaticamente:

**❌ Widget não aparece**

- Verificar se o `merchantId` está correto
- Verificar se o `orderId` está correto
- Conferir console por erros de CORS
- Verificar se o script carregou (`window.PaymentWidget` existe)

Expand Down
42 changes: 21 additions & 21 deletions docs/BOOTSTRAP-EXPLICACAO.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ document.addEventListener("DOMContentLoaded", () => {
const currentScript = document.currentScript;
if (currentScript) {
const config = extractConfigFromDataAttributes(currentScript);
if (config.merchantId) {
if (config.orderId) {
bootstrap.init(config);
}
}
Expand Down Expand Up @@ -71,7 +71,7 @@ document.addEventListener("DOMContentLoaded", () => {
```html
<script>
window.PaymentWidgetInit = {
merchantId: "merchant_123",
orderId: "merchant_123",
theme: {
primaryColor: "#FF6B6B",
},
Expand All @@ -88,7 +88,7 @@ O desenvolvedor pode chamar manualmente após carregar o script:
```javascript
// Aguarda o script estar carregado
await window.PaymentWidget.init({
merchantId: "merchant_123",
orderId: "merchant_123",
theme: {
primaryColor: "#FF6B6B",
secondaryColor: "#4ECDC4",
Expand Down Expand Up @@ -129,7 +129,7 @@ class PaymentWidgetBootstrap {
```
┌─────────────────────────────────────┐
│ 1. Validação ✓ │
│ └─> Verifica merchantId
│ └─> Verifica orderId
│ └─> Verifica duplicação │
└─────────────────────────────────────┘
Expand Down Expand Up @@ -180,8 +180,8 @@ Suporta múltiplos widgets na mesma página (útil para marketplaces):

```javascript
// Inicializa múltiplos merchants
await PaymentWidget.init({ merchantId: "merchant_1" });
await PaymentWidget.init({ merchantId: "merchant_2" });
await PaymentWidget.init({ orderId: "merchant_1" });
await PaymentWidget.init({ orderId: "merchant_2" });

// Controla cada um independentemente
PaymentWidget.open("merchant_1"); // Abre o primeiro
Expand Down Expand Up @@ -306,7 +306,7 @@ private applyTheme(element: HTMLElement, config: WidgetConfig): void {

```javascript
PaymentWidget.init({
merchantId: "merchant_123",
orderId: "merchant_123",
logoUrl: "https://minha-empresa.com/logo.png",
theme: {
primaryColor: "#FF6B6B", // Vermelho coral
Expand Down Expand Up @@ -338,7 +338,7 @@ function extractConfigFromDataAttributes(
const dataset = script.dataset;

return {
merchantId: dataset.merchantId || "",
orderId: dataset.orderId || "",
theme: {
primaryColor: dataset.primary || dataset.primaryColor,
secondaryColor: dataset.secondary || dataset.secondaryColor,
Expand Down Expand Up @@ -379,13 +379,13 @@ window.PaymentWidget = {
init: (config: WidgetConfig) => Promise<void>,

// Abre o modal do widget
open: (merchantId?: string) => void,
open: (orderId?: string) => void,

// Fecha o modal do widget
close: (merchantId?: string) => void,
close: (orderId?: string) => void,

// Remove completamente o widget do DOM
destroy: (merchantId?: string) => void,
destroy: (orderId?: string) => void,

// Retorna o estado atual do widget
getState: () => WidgetState
Expand All @@ -397,7 +397,7 @@ window.PaymentWidget = {
```javascript
// 1. Inicializar o widget
await window.PaymentWidget.init({
merchantId: "merchant_123",
orderId: "merchant_123",
environment: "production",
theme: {
primaryColor: "#FF6B6B",
Expand All @@ -407,7 +407,7 @@ await window.PaymentWidget.init({
// Callbacks
onSuccess: (data) => {
console.log("Pagamento aprovado!", data);
// { transactionId, token, merchantId, amount, ... }
// { transactionId, token, orderId, amount, ... }
},
onError: (error) => {
console.error("Erro no pagamento:", error);
Expand Down Expand Up @@ -581,7 +581,7 @@ const MAX_RETRIES = 50;

```javascript
const container = document.createElement("div");
container.id = `${CONTAINER_ID_PREFIX}${merchantId}`;
container.id = `${CONTAINER_ID_PREFIX}${orderId}`;
container.style.cssText = `
position: fixed; /* Sempre visível mesmo com scroll */
top: 0;
Expand Down Expand Up @@ -706,11 +706,11 @@ console.log("Estado do widget:", state);
### **Problema: "Multiple instances não funcionam"**

```javascript
// Especificar merchantId ao abrir/fechar
// Especificar orderId ao abrir/fechar
PaymentWidget.open("merchant_1");
PaymentWidget.close("merchant_1");

// Sem merchantId, usa o primeiro encontrado
// Sem orderId, usa o primeiro encontrado
PaymentWidget.open(); // Abre primeiro merchant
```

Expand All @@ -729,11 +729,11 @@ PaymentWidget.open(); // Abre primeiro merchant

O **Bootstrap Loader** é essencialmente o **"gerente de carga"** do widget:

✅ Carrega o widget pesado apenas quando necessário
✅ Isola estilos para evitar conflitos
✅ Aplica temas personalizados dinamicamente
✅ Expõe API simples para desenvolvedores
✅ Suporta múltiplas instâncias
✅ Carrega o widget pesado apenas quando necessário
✅ Isola estilos para evitar conflitos
✅ Aplica temas personalizados dinamicamente
✅ Expõe API simples para desenvolvedores
✅ Suporta múltiplas instâncias
✅ Otimizado para performance e cache

Esta arquitetura permite que o widget seja **leve, rápido e flexível**, mantendo uma **excelente experiência de desenvolvedor (DX)** e **performance para o usuário final (UX)**.
18 changes: 9 additions & 9 deletions docs/GUIA-CRIAR-WIDGET-DO-ZERO.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ export default defineConfig({
```typescript
// src/types/index.ts
export interface WidgetConfig {
merchantId: string;
orderId: string;
publicKey: string;
environment?: "sandbox" | "production";
theme?: {
Expand Down Expand Up @@ -432,7 +432,7 @@ export type { WidgetConfig, WidgetInstance, PaymentResult } from "../types";
import { mount } from "@seu-pacote/payment-widget";

const widget = mount(document.getElementById("widget"), {
merchantId: "merchant_123",
orderId: "merchant_123",
publicKey: "pk_live_...",
});

Expand Down Expand Up @@ -496,7 +496,7 @@ window.CartaoSimplesWidget = { mount };
const widget = window.CartaoSimplesWidget.mount(
document.getElementById("payment-widget"),
{
merchantId: "merchant_123",
orderId: "merchant_123",
publicKey: "pk_live_...",
}
);
Expand All @@ -513,7 +513,7 @@ const CDN_BASE_URL = "https://d2x7cg3k3on9lk.cloudfront.net";
const WIDGET_VERSION = "v1";

interface BootstrapConfig {
merchantId: string;
orderId: string;
publicKey: string;
autoOpen?: boolean;
[key: string]: any;
Expand Down Expand Up @@ -599,7 +599,7 @@ class PaymentWidgetBootstrap {
<script>
// Bootstrap carrega o widget sob demanda
window.PaymentWidget.init({
merchantId: "merchant_123",
orderId: "merchant_123",
publicKey: "pk_live_...",
autoOpen: true,
});
Expand Down Expand Up @@ -1000,10 +1000,10 @@ Widget → Tokeniza Cartão → Backend Processa Token → Resposta
### 9.2 Validação de Merchant

```typescript
export async function validateMerchant(merchantId: string): Promise<boolean> {
export async function validateMerchant(orderId: string): Promise<boolean> {
try {
const response = await fetch(
`https://api.seu-backend.com/merchants/${merchantId}/validate`,
`https://api.seu-backend.com/merchants/${orderId}/validate`,
{
headers: {
"X-Public-Key": config.publicKey,
Expand Down Expand Up @@ -1115,7 +1115,7 @@ public/examples/
const widget = window.CartaoSimplesWidget.mount(
document.getElementById("payment-widget"),
{
merchantId: "test_merchant",
orderId: "test_merchant",
publicKey: "pk_test_123",
environment: "sandbox",
}
Expand Down Expand Up @@ -1157,7 +1157,7 @@ describe("PaymentWidget", () => {
render(
<PaymentWidget
config={{
merchantId: "test",
orderId: "test",
publicKey: "pk_test",
}}
/>
Expand Down
Loading