This content is only available in Portuguese.
Migração - Widget Cartão Crédito
MagPay - Migração do Widget de Cartão de Crédito

Para quem é este guia?
Escolha o tipo de integração que você utiliza:
- Integração via iframe (QueryString) - Você incorpora o widget através de um iframe com parâmetros na URL
- Integração via Componente Angular - Você usa o widget como componente Angular em sua aplicação
1. Integração via iframe
1.1 Atualizar a URL do Widget
Antes (Faturamento):
https://widgets.mongeralaegon.com.br/widget-cartao-credito/v3/https://widgets.mongeralaegon.com.br/widget-cartao-credito/v3/Depois (MagPay):
https://widgets.mongeralaegon.com.br/MagPay.Widgets-credit-card/https://widgets.mongeralaegon.com.br/MagPay.Widgets-credit-card/1.2 Atualizar Parâmetros QueryString
Os parâmetros mudaram. Veja o mapeamento:
| Faturamento | MagPay |
|---|---|
acao=PreAutorizacao | isPreApproval=true |
valorCompra=150.00 | purchaseAmount=150.00 |
cnpj, chave, valor | Removidos |
1.3 Enviar Token de Autenticação
postMessage para o iframe:Antes (Faturamento):
window.postMessage({
event: 'notify',
property: 'Auth',
value: 'seu-token-aqui'
}, 'https://widgets.mongeralaegon.com.br');window.postMessage({
event: 'notify',
property: 'Auth',
value: 'seu-token-aqui'
}, 'https://widgets.mongeralaegon.com.br');Depois (MagPay):
const iframe = document.getElementById('magpay-widget').contentWindow;
iframe.postMessage(JSON.stringify({
access_token: 'seu-token-aqui'
}), 'https://widgets.mongeralaegon.com.br');const iframe = document.getElementById('magpay-widget').contentWindow;
iframe.postMessage(JSON.stringify({
access_token: 'seu-token-aqui'
}), 'https://widgets.mongeralaegon.com.br');1.4 Adaptar Pré-Autorização
Para migrar a funcionalidade de Pré-Aprovação do Faturamento para o MagPay, siga estas 3 etapas:
Antes (Faturamento):
Depois (MagPay):
Antes (Faturamento):
window.postMessage({
event: 'notify',
property: 'Auth',
value: 'seu-token-aqui'
}, 'https://widgets.mongeralaegon.com.br');window.postMessage({
event: 'notify',
property: 'Auth',
value: 'seu-token-aqui'
}, 'https://widgets.mongeralaegon.com.br');Depois (MagPay):
const iframe = document.getElementById('magpay-widget').contentWindow;
iframe.postMessage(JSON.stringify({
access_token: 'seu-token-aqui'
}), 'https://widgets.mongeralaegon.com.br');const iframe = document.getElementById('magpay-widget').contentWindow;
iframe.postMessage(JSON.stringify({
access_token: 'seu-token-aqui'
}), 'https://widgets.mongeralaegon.com.br');postMessage:{
"tipo": "cartao-credito-sucesso",
"id": "32c5a91b-d4ba-47d6-9f8d-f1c178e79a25",
"preApprovalId": "a5f18e98-5c14-4a54-8b07-1c510be756eb",
"authorizationCode": 45927
}{
"tipo": "cartao-credito-sucesso",
"id": "32c5a91b-d4ba-47d6-9f8d-f1c178e79a25",
"preApprovalId": "a5f18e98-5c14-4a54-8b07-1c510be756eb",
"authorizationCode": 45927
}CodigoPreAutorizacao foi renomeada para authorizationCodeAtualize a propriedade conforme a tabela abaixo:
| Faturamento (Antes) | MagPay (Depois) |
|---|---|
codigoPreAutorizacao | authorizationCode |
2. Integração via Componente Angular
2.1 Remover pacote antigo
Desinstale o pacote do widget Faturamento:
npm uninstall @mongeral/cartao-credito2.2 Instalar novo pacote
Instale o pacote MagPay versão 19.6.1 ou superior:
npm install @magpay/credit-card@^19.6.12.3 Instalar dependências obrigatórias
Instale as dependências necessárias para autenticação e monitoramento:
npm install @mongeral/componentes-authentication @mongeral/componentes-insights2.4 Configurar app.module.ts
Substitua o import do pacote antigo "@mongeral/cartao-credito" pelo novo pacote "@magpay/credit-card"
import { NgModule } from '@angular/core';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { CreditcardModule } from '@magpay/credit-card'; // Novo pacote MagPay
import { AuthModule } from '@mongeral/componentes-authentication';
import { InsightsModule } from '@mongeral/componentes-insights';
import { environment } from '../environments/environment';
@NgModule({
imports: [
AuthModule.forRoot(environment.authConfig),
InsightsModule.configureInsightsKey(environment.instrumentationKeyFaturamento),
CreditcardModule.forRoot(environment)
],
providers: [
provideHttpClient(withInterceptorsFromDi())
]
})
export class AppModule { }import { NgModule } from '@angular/core';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { CreditcardModule } from '@magpay/credit-card'; // Novo pacote MagPay
import { AuthModule } from '@mongeral/componentes-authentication';
import { InsightsModule } from '@mongeral/componentes-insights';
import { environment } from '../environments/environment';
@NgModule({
imports: [
AuthModule.forRoot(environment.authConfig),
InsightsModule.configureInsightsKey(environment.instrumentationKeyFaturamento),
CreditcardModule.forRoot(environment)
],
providers: [
provideHttpClient(withInterceptorsFromDi())
]
})
export class AppModule { }.forRoot(environment) no Faturamento, mantenha assim. A única mudança é trocar @mongeral/cartao-credito por @magpay/credit-card.2.5 Configuração para Standalone
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptorsFromDi())
]
};import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptorsFromDi())
]
};import { Component } from '@angular/core';
import { CreditcardModule } from '@magpay/credit-card';
@Component({
selector: 'app-payment',
standalone: true,
imports: [CreditcardModule],
template: ''
})
export class PaymentComponent { }import { Component } from '@angular/core';
import { CreditcardModule } from '@magpay/credit-card';
@Component({
selector: 'app-payment',
standalone: true,
imports: [CreditcardModule],
template: ''
})
export class PaymentComponent { }AuthModule e InsightsModule devem ser configurados via providers.2.6 Atualizar template do componente
2.7 Criar objeto Configuration
import { Configuration, ActionType } from '@magpay/credit-card';import { Configuration, ActionType } from '@magpay/credit-card';A interface possui as seguintes propriedades:
interface Configuration {
actionType: ActionType;
purchaseAmount: number;
showCard?: boolean;
cardId?: string;
}
enum ActionType {
PreApproval = 'PreApproval',
Sale = 'Sale'
}interface Configuration {
actionType: ActionType;
purchaseAmount: number;
showCard?: boolean;
cardId?: string;
}
enum ActionType {
PreApproval = 'PreApproval',
Sale = 'Sale'
}Exemplo completo:
import { Component } from '@angular/core';
```json
import { Configuration, ActionType } from '@magpay/credit-card';import { Component } from '@angular/core';
```json
import { Configuration, ActionType } from '@magpay/credit-card';@Component({ selector: 'app-payment', template: '' }) export class PaymentComponent { config: Configuration = { actionType: ActionType.PreApproval, purchaseAmount: 150.00, showCard: true }; }
import { AuthService } from '@mongeral/componentes-authentication';
@Component({ selector: 'app-payment', template: '' }) export class PaymentComponent implements OnInit { config: Configuration = { actionType: ActionType.PreApproval, purchaseAmount: 150.00, showCard: true };
constructor(private authService: AuthService) {}
async ngOnInit() { await this.authService.fetchTokenUsingClientCredentialsFlow({ clientId: 'seu-client-id', clientSecret: 'seu-client-secret', scope: 'apimagpay', tokenUrl: 'https://auth.example.com/oauth/token' }); } }
2.10 Migrar Pré-Autorização
Para migrar do Faturamento para o MagPay, siga estas etapas:
Antes (Faturamento):
DadosRecebidos = {
acao: 'PreAutorizacao',
valorCompra: 150.00,
cnpj: '12345678000190',
chave: ['p1', 'p2'],
valor: ['v1', 'v2']
}DadosRecebidos = {
acao: 'PreAutorizacao',
valorCompra: 150.00,
cnpj: '12345678000190',
chave: ['p1', 'p2'],
valor: ['v1', 'v2']
}Depois (MagPay):
config: Configuration = {
actionType: ActionType.PreApproval,
purchaseAmount: 150.00
}config: Configuration = {
actionType: ActionType.PreApproval,
purchaseAmount: 150.00
}cnpj, chave e valor, pois eles não são mais utilizados no MagPay.Mapeamento das mudanças na configuração:
| Faturamento | MagPay |
|---|---|
acao = 'PreAutorizacao' | actionType = ActionType.PreApproval |
valorCompra | purchaseAmount |
cnpj, chave, valor | Removidos |
postMessage)postMessage:{
"tipo": "cartao-credito-sucesso",
"id": "32c5a91b-d4ba-47d6-9f8d-f1c178e79a25",
"preApprovalId": "a5f18e98-5c14-4a54-8b07-1c510be756eb",
"authorizationCode": 45927
}{
"tipo": "cartao-credito-sucesso",
"id": "32c5a91b-d4ba-47d6-9f8d-f1c178e79a25",
"preApprovalId": "a5f18e98-5c14-4a54-8b07-1c510be756eb",
"authorizationCode": 45927
}CodigoPreAutorizacao foi renomeada para authorizationCodeimport { Component, HostListener } from '@angular/core';
```json
import { Configuration, ActionType } from '@magpay/credit-card';import { Component, HostListener } from '@angular/core';
```json
import { Configuration, ActionType } from '@magpay/credit-card';@Component({ selector: 'app-payment', template: '' }) export class PaymentComponent { config: Configuration = { actionType: ActionType.PreApproval, purchaseAmount: 150.00 };
@HostListener('window:message', ['$event']) onMessage(event: MessageEvent) { if (event.data.Tipo === 'cartao-credito-sucesso') { console.log('PreApproval:', event.data.preApprovalId); console.log('Auth Code:', event.data.authorizationCode); console.log('Card ID:', event.data.id); } if (event.data.Tipo === 'cartao-credito-erro') { console.error(event.data.Mensagens); } } }
?isPreApproval=true&purchaseAmount=150.00`
Parâmetros não reconhecidos
Campo codigoPreAutorizacao não encontrado
codigoPreAutorizacao foi renomeado para authorizationCode. Atualize para authorizationCode na resposta do postMessage.3.2 Problemas com Componente Angular
Cannot find module '@magpay/credit-card'
Pacote não instalado ou não está no package.json.
npm install @magpay/credit-card@^19.6.1CreditcardModule is not imported
import { CreditcardModule } from '@magpay/credit-card';
@NgModule({
imports: [CreditcardModule]
})import { CreditcardModule } from '@magpay/credit-card';
@NgModule({
imports: [CreditcardModule]
})authorizationCode retorna undefined
Token não está sendo enviado
Autenticação não configurada (comum em migração do V2). Implementar OAuth2 Client Credentials (ver seção 4).
Property 'configuration' does not exist
NullInjectorError: No provider for HttpClient
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
CreditcardModule
]
})import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
CreditcardModule
]
})Componente não renderiza / tela em branco
Evento window:message não dispara
Cannot read property 'authConfig' of undefined
export const environment = {
production: false,
authConfig: {
clientId: 'seu-client-id',
authority: 'https://auth.example.com',
// ... outras configs
},
instrumentationKeyFaturamento: 'sua-chave-insights',
// Configurações do widget
apiUrl: 'https://api.example.com',
// ... outras configs necessárias
};export const environment = {
production: false,
authConfig: {
clientId: 'seu-client-id',
authority: 'https://auth.example.com',
// ... outras configs
},
instrumentationKeyFaturamento: 'sua-chave-insights',
// Configurações do widget
apiUrl: 'https://api.example.com',
// ... outras configs necessárias
};TypeError: Cannot read properties of undefined (reading 'forRoot')
O módulo não foi importado corretamente. Verificar se o import está correto:
import { CreditcardModule } from '@magpay/credit-card'; // ✅ Correto
import { CreditcardModule } from '@mongeral/cartao-credito'; // ❌ Erradoimport { CreditcardModule } from '@magpay/credit-card'; // ✅ Correto
import { CreditcardModule } from '@mongeral/cartao-credito'; // ❌ ErradoVersão do Angular incompatível
npm list @angular/coreSe necessário, atualizar o Angular antes de migrar o widget.