Headless SDK
Build your own checkout UI with complete design freedom. The SDK handles card tokenization, 3DS authentication, PIX QR codes, and payment status polling.
What is Headless Mode?
Headless mode gives you full control over the UI while the SDK handles all payment processing logic behind the scenes. You build the forms, collect the data, and design the experience. The SDK takes care of PCI-compliant card tokenization, card brand detection, 3D Secure authentication, PIX QR code handling, and payment status polling.
You handle
- Build your own forms (customer, address, card)
- Design the payment flow and UI
- Display amount breakdown, installments, merchant info
- Show loading states and error messages
SDK handles
- Card tokenization (PCI-compliant, in-browser)
- Card brand detection from BIN
- 3D Secure popup and authentication flow
- PIX QR code display (optional component)
- Payment status polling with exponential backoff
- Device fingerprinting for fraud prevention
Card numbers never leave the browser. The SDK tokenizes them securely via the payment processor before any data is sent to your server or to Glin.
Charge and display totalDueAmount; do not add the parts up. The breakdown in the interactive demo below is illustrative and incomplete: it omits paymentTerms.serviceFeeAmount, so even on an ordinary charge its lines do not sum to its total. Absorption adds a second, separate reason. A charge created with merchantAbsorbsPaymentCosts still reports the full card fee in paymentProcessingFeeAmount while totalDueAmount already excludes it, so a summed total overstates the price by that fee — and a line labelled "processing fee" charges the payer for something the merchant agreed to pay. The same applies to interestRate on an interest-absorbing charge. totalDueAmount and installmentPlans[].totalAmount are the only authoritative figures.
You can also mix and match -- use your own forms for some sections and drop in SDK components for others. For example, build your own customer form but use the SDK's card form component.
Interactive demo
This demo uses tokenizeCard() with a fully custom form. No SDK UI is rendered -- the merchant builds everything and uses checkout.data for amounts and installments.
const checkout = await GlinCheckout.headless({
publicKey: 'YOUR_PUBLIC_KEY',
remittanceId: 'REMITTANCE_ID',
});
// Build your own UI from checkout.data
const { merchant, amount, paymentTerms } = checkout.data;
const cardOption = paymentTerms.options.find(o => o.method === 'CARD');
// On submit: tokenize with YOUR form inputs
const token = await checkout.tokenizeCard({
cardNumber: myForm.cardNumber.value,
cardholderName: myForm.cardName.value,
expirationMonth: myForm.expMonth.value,
expirationYear: myForm.expYear.value,
cvv: myForm.cvv.value,
cpf: customer.taxId,
});
// Send to your backend
const res = await fetch('/api/confirm-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
remittanceId: checkout.data.remittanceId,
paymentData: {
customer, address,
payment: { method: 'card', ...token,
installments: selectedInstallments },
},
}),
}).then(r => r.json());
// Handle 3DS if required
if (res.threeDSecure) {
await checkout.handle3DS(res.threeDSecure.externalResourceUrl, res.threeDSecure.creq);
}
checkout.pollStatus({
onConfirmed: () => window.location.href = '/success',
}).start();Prerequisites
- remittanceId -- Create a remittance via
POST /merchant-api/remittances/from your server. See Step 1 of the Integration Guide. - publicKey -- Your checkout public key from the merchant dashboard.
- Backend endpoint -- A server endpoint that receives payment data and calls
POST /merchant-api/remittances/{'{id}'}/paywith your API key.
Make sure you have the SDK loaded on your page before using the examples below. See Getting Started for the CDN script tag or npm installation.
Step 1: Initialize Headless Checkout
Call GlinCheckout.headless() with your public key and remittance ID. This fetches checkout data (amount, merchant info, payment options) and prepares the payment processor in the background.
Script Tag (UMD)
<script src="https://sdk.glin.com.br/v1/glin-checkout.js"></script>
<script>
const checkout = await GlinCheckout.headless({
publicKey: 'pk_stag_abc123', // Your public key (staging)
remittanceId: 'rem_xyz', // From your backend (Step 1 of Integration Guide)
locale: 'en', // Card form language. Defaults to 'pt-BR' (SDK 1.1.0+)
});
// checkout.data contains everything you need to build your UI
console.log(checkout.data.amount); // { amount: 2850, currency: 'BRL', ... }
console.log(checkout.data.merchant); // { name: 'Acme Inc', logoUrl: '...' }
console.log(checkout.data.paymentTerms); // { options: [...], taxRate, taxAmount, ... }
</script>npm / ES Module
import { GlinCheckout } from '@glin/checkout-sdk';
const checkout = await GlinCheckout.headless({
publicKey: 'pk_stag_abc123',
remittanceId: remittanceId,
locale: 'en', // Card form language. Defaults to 'pt-BR' (SDK 1.1.0+)
}); The SDK auto-detects the environment from your public key prefix. pk_stag_ routes to staging, pk_prod_ routes to production.
Step 2: Display Checkout Information
After initialization, checkout.data contains everything you need to build your checkout UI -- amount breakdown, merchant details, available payment methods, and installment plans.
// Amount info
const { amount, merchant, paymentTerms } = checkout.data;
// Format for display
const totalBRL = amount.amount.toLocaleString('pt-BR', {
style: 'currency',
currency: amount.currency,
}); // "R$ 2.850,00"
const sourceDisplay = amount.sourceAmount.toLocaleString('en-US', {
style: 'currency',
currency: amount.sourceCurrency,
}); // "$500.00"
// Show merchant info
document.getElementById('merchant-name').textContent = merchant.name;
if (merchant.logoUrl) {
document.getElementById('merchant-logo').src = merchant.logoUrl;
}
// List available payment methods
const cardOption = paymentTerms.options.find(o => o.method === 'CARD');
const pixOption = paymentTerms.options.find(o => o.method === 'PIX');
// Show installment plans (card only). This list is already what the charge offers:
// one created with maxInstallments carries fewer plans, so render what you receive
// instead of a fixed range -- /pay refuses a count that is not in it.
if (cardOption) {
const singlePayment = cardOption.installmentPlans.find(plan => plan.installments === 1);
cardOption.installmentPlans.forEach(plan => {
const installmentDisplay = plan.installmentAmount.toLocaleString('pt-BR', {
style: 'currency', currency: 'BRL',
});
// Check both the rate and the totals; neither is enough alone. When the merchant absorbs
// the interest (interestFreeInstallmentsUpTo on the charge), interestRate stays at the
// contract's rate while totalAmount drops to the single-payment total -- so the rate
// alone would hide exactly the installments the merchant is paying for. And a plan your
// contract prices at zero can total a cent above the single payment once each
// installment is rounded to cents -- so the totals alone would hide that one.
const interestFree = plan.interestRate <= 0
|| (singlePayment && plan.totalAmount <= singlePayment.totalAmount);
console.log(
plan.installments === 1
? `1x de ${installmentDisplay} (a vista)`
: `${plan.installments}x de ${installmentDisplay}${interestFree ? ' sem juros' : ''}`
);
});
}CheckoutData Fields
| Name | Type | Required | Description |
|---|---|---|---|
remittanceId | string | — | The remittance ID for this payment. |
merchant | MerchantInfo | — | { name, slug, logoUrl } -- merchant display information. |
amount | AmountInfo | — | { amount, currency, sourceAmount, sourceCurrency, exchangeRate, conversionRate } -- full amount breakdown. |
paymentTerms | PaymentTermsInfo | — | { taxRate, taxAmount, serviceFeeAmount, options[] } -- taxes, fees, and available payment methods. |
paymentTerms.options[] | PaymentOptionInfo | — | { method, totalDueAmount, paymentProcessingFeeAmount, installmentPlans[] } -- one entry per payment method (CARD, PIX). totalDueAmount is what to charge and what to show: the components do not always sum to it. paymentProcessingFeeAmount is the fee the contract prices, and it is not removed when the merchant absorbs it -- a charge created with merchantAbsorbsPaymentCosts still reports the full card fee here while totalDueAmount already excludes it, so adding the parts up overstates the price by that fee. |
installmentPlans[] | InstallmentPlanInfo | — | { installments, installmentAmount, totalAmount, interestRate } -- available installment options for card payments. interestRate is the rate the contract prices for that plan and does not reflect interest the merchant absorbed: when the charge carries interestFreeInstallmentsUpTo, totalAmount drops to the single-payment total while interestRate stays as priced. |
expiresInSeconds | number | — | Seconds until this checkout expires. Show a countdown timer if desired. |
Step 3: Collect Payment Data
Build your own forms to collect customer info, address, and payment details. You have two approaches:
Option A: Build 100% custom forms
Create your own HTML/React/Vue forms. The SDK just needs the data when the user clicks Pay. These are the fields you need to collect:
| Section | Fields | Notes |
|---|---|---|
| Customer | taxId (CPF), name, email, phone | CPF mask is stripped automatically by tokenizeCard(). Phone is sent as E.164. |
| Address | zipCode, street, number, complement (optional), neighborhood, city, state | Brazilian address. CEP auto-fill is handled if you use renderAddressFields() |
| Card | cardNumber, cardholderName, expirationMonth, expirationYear, cvv | Pass to tokenizeCard() -- never send to your server |
| PIX | No additional fields | Just set payment.method: 'pix' |
For card payments, you can detect the brand as the user types to show an icon:
// As the user types their card number, detect the brand for your UI
cardNumberInput.addEventListener('input', async () => {
const digits = cardNumberInput.value.replace(/\D/g, '');
if (digits.length >= 6) {
const brand = await checkout.detectCardBrand(digits);
// brand = 'visa', 'mastercard', 'amex', 'elo', or null
if (brand) {
brandIcon.src = `/icons/${brand}.svg`;
brandIcon.style.display = '';
}
}
});Option B: Use SDK components in your layout
Drop pre-built SDK components into your containers. They include input masking, validation, CEP auto-lookup, and card brand detection out of the box.
// Instead of building your own form fields, use SDK components:
const customerFields = checkout.renderCustomerFields('#my-customer-div');
const addressFields = checkout.renderAddressFields('#my-address-div');
const cardForm = checkout.renderCardForm('#my-card-div', (installments) => {
// Called when user selects a different installment plan
updateTotalDisplay(installments);
});
// On submit, get the data from our components:
const customer = customerFields.getData(); // { taxId, name, email, phone } with phone as E.164
const address = addressFields.getData(); // { zipCode, street, number, ... }
const cardData = await cardForm.getCardData(customer.taxId);
// cardData = { token, paymentMethodId, installments, deviceId }Mix and match freely. Use the SDK card form but your own address form, or use SDK customer fields but build everything else custom.
Step 4: Tokenize Card (Card Payments Only)
When the user clicks Pay with a card, call tokenizeCard() to securely convert the card data into a token. This is required for PCI compliance -- card numbers never touch your server.
// When the user clicks "Pay", tokenize their card data.
// Card numbers NEVER leave the browser -- they are tokenized securely
// by Glin's payment processor before being sent anywhere.
const token = await checkout.tokenizeCard({
cardNumber: '4509 9535 6623 3704', // spaces are stripped automatically
cardholderName: 'MARIA SILVA',
expirationMonth: '12',
expirationYear: '28', // 2-digit or 4-digit year accepted
cvv: '123',
cpf: '123.456.789-09', // mask is stripped automatically
});
// token = {
// token: 'abc123...', // secure token (NOT the card number)
// paymentMethodId: 'visa', // detected card brand
// deviceId: 'xyz...', // device fingerprint for fraud prevention
// }tokenizeCard() Parameters
| Name | Type | Required | Description |
|---|---|---|---|
cardNumber | string | — | Full card number. Spaces and masks are stripped automatically. |
cardholderName | string | — | Name as printed on the card. Automatically uppercased. |
expirationMonth | string | — | Two-digit month (e.g. "01", "12"). |
expirationYear | string | — | Two-digit or four-digit year (e.g. "28" or "2028"). |
cvv | string | — | Card verification code (3 or 4 digits). |
cpf | string | — | Customer CPF (tax ID). Mask is stripped automatically. |
For PIX payments, skip this step. PIX does not require card data. Just set payment.method: 'pix' in the PayRequest (Step 5).
Using the SDK card form component? Call cardForm.getCardData(cpf) instead of tokenizeCard(). It returns the same token data plus the selected installment count.
Step 5: Submit Payment
Build the PayRequest object with all collected data and send it to your backend. Your backend forwards it to Glin's API with your secret API key.
Card PayRequest
// Build the PayRequest object
const payRequest = {
customer: {
taxId: '12345678900', // CPF, digits only
name: 'Maria Silva',
email: 'maria@example.com',
phone: '+5511999999999', // required, E.164
},
address: {
zipCode: '01001000', // digits only
street: 'Praca da Se',
number: '1',
complement: '', // optional
neighborhood: 'Se',
city: 'Sao Paulo',
state: 'SP',
},
payment: {
method: 'card',
token: token.token, // from tokenizeCard()
paymentMethodId: token.paymentMethodId,
installments: 3, // from your selector; must be one of the
// plans cardOption.installmentPlans offered
deviceId: token.deviceId, // from tokenizeCard()
},
};PIX PayRequest
// For PIX, the payment object is simpler -- no tokenization needed
const payRequest = {
customer: {
taxId: '12345678900',
name: 'Maria Silva',
email: 'maria@example.com',
phone: '+5511999999999', // required, E.164
},
address: {
zipCode: '01001000',
street: 'Praca da Se',
number: '1',
neighborhood: 'Se',
city: 'Sao Paulo',
state: 'SP',
},
payment: {
method: 'pix', // no token, no installments
},
};Send to your backend
// Send payRequest to YOUR backend
const response = await fetch('/api/confirm-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
remittanceId: checkout.data.remittanceId,
paymentData: payRequest,
}),
}).then(r => r.json());Your backend (forward to Glin)
// Your backend (server.js) -- forward to Glin with your secret API key
app.post('/api/confirm-payment', async (req, res) => {
const { remittanceId, paymentData } = req.body;
const response = await fetch(
GLIN_BASE_URL + '/merchant-api/remittances/' + remittanceId + '/pay',
{
method: 'POST',
headers: {
'Authorization': 'Bearer ' + GLIN_API_KEY, // your secret API key
'Content-Type': 'application/json',
},
body: JSON.stringify(paymentData),
},
);
const result = await response.json();
res.json(result); // Forward response back to the frontend
}); Never expose your API key in client-side code. The payment confirmation must happen on your backend using your secret Authorization: Bearer token.
Step 6: Handle the Response
The response from your backend indicates what happens next. There are three possible cases:
// The response from your backend will look like this:
// {
// orderId: 'ord_abc123',
// status: 'PROCESSING',
// pix?: { qrCode: '00020126...', qrCodeImage: 'data:image/png;base64,...' },
// threeDSecure?: { externalResourceUrl: 'https://...', creq: '...' },
// }
// CASE 1: Card payment approved (no 3DS required)
// response has orderId and status only --> go straight to polling
// CASE 2: Card payment requires 3DS verification
if (response.threeDSecure) {
showMessage('Complete bank verification in the popup...');
await checkout.handle3DS(response.threeDSecure.externalResourceUrl, response.threeDSecure.creq);
// Popup closed -- now poll for result
}
// CASE 3: PIX payment -- show QR code
if (response.pix) {
// Option A: Use our QR component (styled, with copy button)
checkout.renderPixDisplay('#qr-container', response.pix);
// Option B: Render it yourself
// qrImage.src = response.pix.qrCodeImage; // base64 PNG
// qrCodeText.textContent = response.pix.qrCode; // copy-paste string
}| Scenario | Response Contains | Your Action |
|---|---|---|
| Card (no 3DS) | orderId, status | Go straight to polling (Step 7) |
| Card (3DS required) | threeDSecure.externalResourceUrl | Call checkout.handle3DS(url, creq), then poll |
| PIX | pix.qrCode, pix.qrCodeImage | Show QR code, then poll for confirmation |
Step 7: Poll for Payment Confirmation
After submitting the payment (and handling 3DS or displaying the PIX QR code), poll for the final status. The SDK handles exponential backoff automatically.
const poller = checkout.pollStatus({
onConfirmed: (status) => {
// Payment successful!
window.location.href = '/order/success';
},
onRejected: (status) => {
// Payment was not approved
showError('Payment was not approved. Please try again.');
},
onError: (error) => {
// Network or polling error
console.error('Polling error:', error.message);
},
});
// Start polling
poller.start();
// To stop polling early (e.g., user navigates away):
// poller.stop();The SDK polls with exponential backoff (2s intervals increasing to 10s). It stops automatically after ~4 minutes or when a terminal status is reached (confirmed or rejected).
Don't rely solely on polling for order fulfillment. Set up a webhook on your backend for reliable payment confirmation.
Complete Examples
Copy-paste ready examples for common scenarios. Each is a self-contained HTML file you can open directly in the browser.
Full Card Payment
<!DOCTYPE html>
<html>
<head>
<title>Card Payment - Headless</title>
<script src="https://sdk.glin.com.br/v1/glin-checkout.js"></script>
</head>
<body>
<h1>Pay with Card</h1>
<form id="payment-form">
<!-- Customer -->
<input id="cpf" placeholder="CPF" />
<input id="name" placeholder="Full name" />
<input id="email" type="email" placeholder="Email" />
<input id="phone" type="tel" placeholder="Phone (E.164)" />
<!-- Address -->
<input id="zipCode" placeholder="CEP" />
<input id="street" placeholder="Street" />
<input id="number" placeholder="Number" />
<input id="neighborhood" placeholder="Neighborhood" />
<input id="city" placeholder="City" />
<input id="state" placeholder="State" />
<!-- Card -->
<input id="cardNumber" placeholder="Card number" />
<input id="cardName" placeholder="Name on card" />
<input id="expMonth" placeholder="MM" />
<input id="expYear" placeholder="YY" />
<input id="cvv" placeholder="CVV" />
<!-- Installments (populated by JS) -->
<select id="installments"></select>
<button type="submit">Pay</button>
</form>
<div id="result"></div>
<script>
(async () => {
// 1. Initialize headless checkout
const checkout = await GlinCheckout.headless({
publicKey: 'pk_stag_abc123',
remittanceId: 'rem_xyz', // from your backend
});
// 2. Populate installment options
const cardOption = checkout.data.paymentTerms.options.find(o => o.method === 'CARD');
const select = document.getElementById('installments');
const singlePayment = cardOption.installmentPlans.find(plan => plan.installments === 1);
cardOption.installmentPlans.forEach(plan => {
const opt = document.createElement('option');
opt.value = plan.installments;
const amt = plan.installmentAmount.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
// Check both: absorbed interest keeps the contract rate, and cent rounding can lift a 0% total.
const interestFree = plan.interestRate <= 0
|| (singlePayment && plan.totalAmount <= singlePayment.totalAmount);
opt.textContent = plan.installments === 1
? `1x de ${amt} (a vista)`
: `${plan.installments}x de ${amt}${interestFree ? ' sem juros' : ''}`;
select.appendChild(opt);
});
// 3. Handle form submit
document.getElementById('payment-form').addEventListener('submit', async (e) => {
e.preventDefault();
// 4. Tokenize card
const token = await checkout.tokenizeCard({
cardNumber: document.getElementById('cardNumber').value,
cardholderName: document.getElementById('cardName').value,
expirationMonth: document.getElementById('expMonth').value,
expirationYear: document.getElementById('expYear').value,
cvv: document.getElementById('cvv').value,
cpf: document.getElementById('cpf').value,
});
// 5. Send to your backend
const response = await fetch('/api/confirm-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
remittanceId: checkout.data.remittanceId,
paymentData: {
customer: {
taxId: document.getElementById('cpf').value.replace(/\D/g, ''),
name: document.getElementById('name').value,
email: document.getElementById('email').value,
phone: document.getElementById('phone').value.trim(),
},
address: {
zipCode: document.getElementById('zipCode').value.replace(/\D/g, ''),
street: document.getElementById('street').value,
number: document.getElementById('number').value,
neighborhood: document.getElementById('neighborhood').value,
city: document.getElementById('city').value,
state: document.getElementById('state').value,
},
payment: {
method: 'card',
token: token.token,
paymentMethodId: token.paymentMethodId,
installments: parseInt(select.value),
deviceId: token.deviceId,
},
},
}),
}).then(r => r.json());
// 6. Handle 3DS if required
if (response.threeDSecure) {
await checkout.handle3DS(response.threeDSecure.externalResourceUrl, response.threeDSecure.creq);
}
// 7. Poll for confirmation
checkout.pollStatus({
onConfirmed: () => {
document.getElementById('result').textContent = 'Payment confirmed!';
},
onRejected: () => {
document.getElementById('result').textContent = 'Payment rejected.';
},
}).start();
});
})();
</script>
</body>
</html>Full PIX Payment
<!DOCTYPE html>
<html>
<head>
<title>PIX Payment - Headless</title>
<script src="https://sdk.glin.com.br/v1/glin-checkout.js"></script>
</head>
<body>
<h1>Pay with PIX</h1>
<form id="payment-form">
<input id="cpf" placeholder="CPF" />
<input id="name" placeholder="Full name" />
<input id="email" type="email" placeholder="Email" />
<input id="phone" type="tel" placeholder="Phone (E.164)" />
<input id="zipCode" placeholder="CEP" />
<input id="street" placeholder="Street" />
<input id="number" placeholder="Number" />
<input id="neighborhood" placeholder="Neighborhood" />
<input id="city" placeholder="City" />
<input id="state" placeholder="State" />
<button type="submit">Generate PIX</button>
</form>
<div id="qr-container" style="display:none"></div>
<div id="result"></div>
<script>
(async () => {
const checkout = await GlinCheckout.headless({
publicKey: 'pk_stag_abc123',
remittanceId: 'rem_xyz',
});
document.getElementById('payment-form').addEventListener('submit', async (e) => {
e.preventDefault();
// No tokenization needed for PIX
const response = await fetch('/api/confirm-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
remittanceId: checkout.data.remittanceId,
paymentData: {
customer: {
taxId: document.getElementById('cpf').value.replace(/\D/g, ''),
name: document.getElementById('name').value,
email: document.getElementById('email').value,
phone: document.getElementById('phone').value.trim(),
},
address: {
zipCode: document.getElementById('zipCode').value.replace(/\D/g, ''),
street: document.getElementById('street').value,
number: document.getElementById('number').value,
neighborhood: document.getElementById('neighborhood').value,
city: document.getElementById('city').value,
state: document.getElementById('state').value,
},
payment: { method: 'pix' },
},
}),
}).then(r => r.json());
// Show QR code using SDK component
if (response.pix) {
document.getElementById('qr-container').style.display = '';
checkout.renderPixDisplay('#qr-container', response.pix);
}
// Poll until customer scans and pays
checkout.pollStatus({
onConfirmed: () => {
document.getElementById('result').textContent = 'PIX payment confirmed!';
},
}).start();
});
})();
</script>
</body>
</html>Mixed: Your Layout + SDK Components
// Use SDK components for customer/card but your own layout and address form
const checkout = await GlinCheckout.headless({
publicKey: 'pk_stag_abc123',
remittanceId: 'rem_xyz',
});
// Mount SDK components in your containers
const customerFields = checkout.renderCustomerFields('#customer-section', {
data: { name: 'Maria Silva', email: 'maria@example.com' }, // pre-fill
visibility: { email: 'readOnly' }, // lock email
});
const cardForm = checkout.renderCardForm('#card-section', (installments) => {
document.getElementById('total').textContent =
checkout.data.paymentTerms.options
.find(o => o.method === 'CARD')
.installmentPlans
.find(p => p.installments === installments)
.totalAmount.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
});
// On submit
document.getElementById('pay-btn').addEventListener('click', async () => {
// Validate SDK components
if (customerFields.validate().length) return;
const customer = customerFields.getData(); // phone is E.164
const cardData = await cardForm.getCardData(customer.taxId);
const address = getMyCustomAddressData(); // your own address form
const response = await fetch('/api/confirm-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
remittanceId: checkout.data.remittanceId,
paymentData: {
customer,
address,
payment: {
method: 'card',
token: cardData.token,
paymentMethodId: cardData.paymentMethodId,
installments: cardData.installments,
deviceId: cardData.deviceId,
},
},
}),
}).then(r => r.json());
if (response.threeDSecure) {
await checkout.handle3DS(response.threeDSecure.externalResourceUrl, response.threeDSecure.creq);
}
checkout.pollStatus({
onConfirmed: () => window.location.href = '/success',
onRejected: () => showError('Payment rejected'),
}).start();
});React
import { useEffect, useRef, useState } from 'react';
export default function HeadlessCheckout({ remittanceId }) {
const [checkout, setCheckout] = useState(null);
const [brand, setBrand] = useState(null);
const cardRef = useRef(null);
const customerRef = useRef(null);
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://sdk.glin.com.br/v1/glin-checkout.js';
script.onload = async () => {
const instance = await GlinCheckout.headless({
publicKey: process.env.NEXT_PUBLIC_GLIN_PUBLIC_KEY,
remittanceId,
});
setCheckout(instance);
// Mount SDK components
instance.renderCustomerFields(customerRef.current);
instance.renderCardForm(cardRef.current);
};
document.head.appendChild(script);
return () => script.remove();
}, [remittanceId]);
if (!checkout) return <div>Loading checkout...</div>;
const { amount, merchant } = checkout.data;
return (
<div>
<h2>{merchant.name}</h2>
<p>Total: {amount.amount.toLocaleString('pt-BR', {
style: 'currency', currency: amount.currency
})}</p>
<div ref={customerRef} />
{/* Your own address form here */}
<div ref={cardRef} />
<button onClick={handleSubmit}>Pay</button>
</div>
);
}Vue 3
<script setup>
import { ref, onMounted } from 'vue'
const props = defineProps({ remittanceId: String })
const checkout = ref(null)
const customerContainer = ref(null)
const cardContainer = ref(null)
onMounted(async () => {
const script = document.createElement('script')
script.src = 'https://sdk.glin.com.br/v1/glin-checkout.js'
document.head.appendChild(script)
await new Promise(resolve => script.onload = resolve)
checkout.value = await GlinCheckout.headless({
publicKey: globalThis._importMeta_.env.VITE_GLIN_PUBLIC_KEY,
remittanceId: props.remittanceId,
})
// Mount SDK components
checkout.value.renderCustomerFields(customerContainer.value)
checkout.value.renderCardForm(cardContainer.value)
})
</script>
<template>
<div v-if="!checkout">Loading checkout...</div>
<div v-else>
<h2>{{ checkout.data.merchant.name }}</h2>
<div ref="customerContainer" />
<!-- Your own address form here -->
<div ref="cardContainer" />
<button @click="handleSubmit">Pay</button>
</div>
</template>API Reference
Core Methods
These methods handle the payment processing logic. Use them with your own UI.
| Name | Type | Required | Description |
|---|---|---|---|
checkout.data | CheckoutData | — | Access checkout data: amount, merchant info, payment options, installment plans. Available immediately after initialization. |
checkout.tokenizeCard(input) | Promise<CardTokenResult> | — | PCI-compliant card tokenization. Card numbers never leave the browser. Returns { token, paymentMethodId, deviceId }. |
checkout.detectCardBrand(bin) | Promise<string | null> | — | Detect card brand from first 6+ digits. Returns "visa", "mastercard", "amex", "elo", or null. |
checkout.handle3DS(url, creq) | Promise<void> | — | Opens a 3D Secure popup for bank verification. Pass both fields from threeDSecure: the ACS requires creq to be POSTed and answers a plain GET with an error page. Resolves when the popup is closed (user completed auth or dismissed it). |
checkout.pollStatus(callbacks) | { start(), stop() } | — | Poll for payment confirmation with exponential backoff (2s to 10s). Stops on a terminal paymentStatus, orderStatus or remittanceStatus, or after the checkout window (clamped to 20-45 min) via onTimeout. Fires onChallenge when the provider raises 3D Secure after the pay call returned. |
Optional Render Methods
Drop SDK-styled components into your layout. Each returns an object with methods to get data, validate, and control visibility.
| Name | Type | Required | Description |
|---|---|---|---|
checkout.renderCardForm(el, onInstChange?) | { getCardData(cpf), show(), hide() } | — | Mount the SDK styled card form with number, name, expiry, CVV, and installment selector. |
checkout.renderPixDisplay(el, pix) | { show(), hide(), destroy() } | — | Mount a PIX QR code display with the QR image, copy-paste code, and waiting indicator. |
checkout.renderCustomerFields(el, opts?) | { getData(), validate(), setDisabled() } | — | Mount customer fields (CPF with mask, name, email, phone). Supports pre-fill and visibility control. |
checkout.renderAddressFields(el, opts?) | { getData(), validate() } | — | Mount address fields with CEP auto-lookup via ViaCEP. Supports pre-fill and visibility control. |
Testing
Use the staging environment (pk_stag_ prefix) with test credentials.
Test Card Numbers
| Brand | Number | Notes |
|---|---|---|
| Visa | 4509 9535 6623 3704 | Test Visa card. CVV: 123, any future expiration. |
| Mastercard | 5031 4332 1540 6351 | Test Mastercard. CVV: 123, any future expiration. |
Simulate Payment Results
The cardholder name controls the payment outcome in staging:
| Cardholder Name | Result | Description |
|---|---|---|
| APRO | Approved | Payment is approved. |
| OTHE | Rejected | Payment is rejected (general error). |
| CONT | Pending | Payment stays in pending status. |
For PIX in staging, payments are auto-confirmed. Use any valid CPF format for the customer tax ID (e.g. 123.456.789-09). For a complete testing reference, see the Testing Guide.
Next Steps
Explore related topics: