Após feito a request, existe um campo que o MercadoPago envia, sendo o Qrcode. Com o código que vou fornecer abaixo, você pode conseguir chegar nesse resultado se quiser.
Neste post, vamos explorar como integrar o PIX, um método de pagamento instantâneo brasileiro, em sua aplicação FrontEnd usando apenas JavaScript e a API do Mercado Pago. Ideal para desenvolvedores que buscam implementar uma solução de pagamento ágil e segura.
###Documentação Essencial 📚
Antes de mergulhar na codificação, é crucial familiarizar-se com a [documentação oficial do Mercado Pago] https://www.mercadopago.com.br/developers/pt/docs/checkout-api/integration-configuration/integrate-with-pix. Aqui, você encontrará um guia completo com o código.
### Preparando o Ambiente 🛠️
- Conta no Mercado Pago: Comece criando uma conta no [Painel do Desenvolvedor do Mercado Pago]: https://www.mercadopago.com.br/developers/panel/app para obter suas credenciais de API.
Editor: Recomendo o VSCode para um ambiente de desenvolvimento.
Postman: Essencial para testar e validar suas requisições à API antes de integrá-las ao seu projeto.
### Implementação PIX com JavaScript 🔧
Setup Inicial: Crie um index.html e script.js como base do seu projeto.
./index.html
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8" />
<title>Integração Mercado Pago</title>
<script src="https://sdk.mercadopago.com/js/v2"></script>
<script src="script.js" defer></script>
<style>
body {
background-color: rgb(147, 135, 135);
}
</style>
</head>
<body>
<form id="form-checkout">
<div>
<label for="payerFirstName">Nome</label>
<input
id="form-checkout__payerFirstName"
name="payerFirstName"
type="text"
value="Gérson TEST PIX"
/>
</div>
<div>
<label for="payerLastName">Sobrenome</label>
<input
id="form-checkout__payerLastName"
name="payerLastName"
type="text"
value="Aguiar TEST PIX"
/>
</div>
<div>
<label for="email">E-mail</label>
<input
id="form-checkout__email"
name="email"
type="text"
value="gersonTESTPIX@gmail.com"
/>
</div>
<div>
<label for="identificationType">Tipo de documento</label>
<select
id="form-checkout__identificationType"
name="identificationType"
></select>
</div>
<div>
<label for="identificationNumber">Número do documento</label>
<input
id="form-checkout__identificationNumber"
name="identificationNumber"
type="text"
value="01234567890"
/>
</div>
<input
type="hidden"
name="transactionAmount"
id="transactionAmount"
value="2"
/>
<input
type="hidden"
name="description"
id="description"
value="Produto TEST PIX"
/>
<button type="submit">Pagar</button>
</form>
</body>
</html>
./script.js
document.addEventListener('DOMContentLoaded', function () {
const PUBLIC_KEY = 'PEGUE_SEU_NO_PAINEL_DO_MERCADOPAGO';
const ACCESS_TOKEN = 'PEGUE_SEU_NO_PAINEL_DO_MERCADOPAGO';
const mp = new MercadoPago(PUBLIC_KEY);
getIdentificationTypes(mp);
const form = document.getElementById('form-checkout');
form.addEventListener('submit', async function (e) {
e.preventDefault(); // Evita a submissão tradicional do formulário
const paymentMethodId = 'pix';
const transactionAmount =
document.getElementById('transactionAmount').value;
// pegando valores do formulario
const email = document.getElementById('form-checkout__email').value;
const firstName = document.getElementById(
'form-checkout__payerFirstName'
).value;
const lastName = document.getElementById(
'form-checkout__payerLastName'
).value;
const identificationType = document.getElementById(
'form-checkout__identificationType'
).value;
const identificationNumber = document.getElementById(
'form-checkout__identificationNumber'
).value;
const paymentData = {
transaction_amount: parseFloat(transactionAmount),
description: 'Descrição do Produto',
payment_method_id: paymentMethodId,
payer: {
email: email,
first_name: firstName,
last_name: lastName,
identification: {
type: identificationType,
number: identificationNumber,
},
},
notification_url: '',
};
const response = await fetch('https://api.mercadopago.com/v1/payments', {
method: 'POST',
headers: {
accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${ACCESS_TOKEN}`,
'X-Idempotency-Key': `${Math.random().toString(36).substr(2, 9)}`, // Gera um valor único
},
body: JSON.stringify(paymentData),
});
if (!response.ok) {
throw new Error('Falha ao processar o pagamento');
}
const responseData = await response.json();
// Se tudo der certo, você deve ver o QRCode, que pode ser pago, nesse campo da response
console.log( responseData.point_of_interaction.transaction_data.ticket_url)
});
});
async function getIdentificationTypes(mp) {
try {
const identificationTypes = await mp.getIdentificationTypes();
const identificationTypeElement = document.getElementById(
'form-checkout__identificationType'
);
createSelectOptions(identificationTypeElement, identificationTypes);
} catch (e) {
console.error('Error getting identificationTypes: ', e);
}
}
function createSelectOptions(
elem,
options,
labelsAndKeys = { label: 'name', value: 'id' }
) {
elem.options.length = 0;
options.forEach((option) => {
const opt = new Option(
option[labelsAndKeys.label],
option[labelsAndKeys.value]
);
elem.add(opt);
});
}
Request HTTP: Dedique um tempo para entender os parâmetros na request.
Response e QR Code: Dedique um tempo para entender a response.
Próximos Passos: Sugestões para expandir suas habilidades e integrações de pagamento.
Quer ter acesso ao Código completo? 📢
FrontEnd com o JavaScript? 📢
BackEnd uma aplicação em Micronaut com Kotlin?
Acesse o link: https://www.instagram.com/gersonaguiar.br/
Interessado em aprofundar seus conhecimentos e implementar uma solução de pagamento PIX no seu projeto FrontEnd ou BackEnd?