Exemplos de Código
Exemplos completos de integração com a API EloFiel em quatro linguagens. Todos os exemplos utilizam autenticação por X-Api-Key e são prontos para uso em produção com pequenas adaptações.
Configuração inicial
- cURL
- JavaScript / Node.js
- PHP
- Python
# Defina as variáveis no shell
export ELOFIEL_API_KEY="sua_api_key_aqui"
export ELOFIEL_BASE_URL="https://api-sandbox.elofiel.com.br"
export CNPJ_LOJA="12.345.678/0001-90"
// config/elofiel.js
const ELOFIEL_CONFIG = {
baseUrl: process.env.ELOFIEL_BASE_URL ?? 'https://api-sandbox.elofiel.com.br',
apiKey: process.env.ELOFIEL_API_KEY,
cnpjLoja: process.env.CNPJ_LOJA ?? '12.345.678/0001-90',
};
async function eloFielFetch(method, path, body = null) {
const response = await fetch(`${ELOFIEL_CONFIG.baseUrl}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
'X-Api-Key': ELOFIEL_CONFIG.apiKey,
},
body: body ? JSON.stringify(body) : undefined,
});
const resultado = await response.json();
if (!resultado.sucesso) {
const mensagem = resultado.erros?.[0] ?? resultado.mensagem ?? 'Erro desconhecido';
const erro = new Error(mensagem);
erro.status = response.status;
erro.erros = resultado.erros;
throw erro;
}
return resultado.dados;
}
module.exports = { ELOFIEL_CONFIG, eloFielFetch };
<?php
// config/elofiel.php
define('ELOFIEL_BASE_URL', getenv('ELOFIEL_BASE_URL') ?: 'https://api-sandbox.elofiel.com.br');
define('ELOFIEL_API_KEY', getenv('ELOFIEL_API_KEY'));
define('CNPJ_LOJA', getenv('CNPJ_LOJA') ?: '12.345.678/0001-90');
function eloFielRequest(string $method, string $path, ?array $body = null): array {
$ch = curl_init(ELOFIEL_BASE_URL . $path);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-Api-Key: ' . ELOFIEL_API_KEY,
],
CURLOPT_POSTFIELDS => $body ? json_encode($body) : null,
CURLOPT_TIMEOUT => 10,
]);
$resposta = json_decode(curl_exec($ch), true);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!$resposta['sucesso']) {
$mensagem = $resposta['erros'][0] ?? $resposta['mensagem'] ?? 'Erro desconhecido';
throw new RuntimeException($mensagem, $httpCode);
}
return $resposta['dados'];
}
# config/elofiel.py
import os
import requests
ELOFIEL_BASE_URL = os.getenv('ELOFIEL_BASE_URL', 'https://api-sandbox.elofiel.com.br')
ELOFIEL_API_KEY = os.getenv('ELOFIEL_API_KEY')
CNPJ_LOJA = os.getenv('CNPJ_LOJA', '12.345.678/0001-90')
def elofiel_request(method: str, path: str, body: dict = None) -> dict:
headers = {
'Content-Type': 'application/json',
'X-Api-Key': ELOFIEL_API_KEY,
}
response = requests.request(
method=method,
url=f'{ELOFIEL_BASE_URL}{path}',
headers=headers,
json=body,
timeout=10,
)
resultado = response.json()
if not resultado.get('sucesso'):
erros = resultado.get('erros', [])
mensagem = erros[0] if erros else resultado.get('mensagem', 'Erro desconhecido')
raise ValueError(f'EloFiel API error ({response.status_code}): {mensagem}')
return resultado['dados']
Obter Configuração
- cURL
- JavaScript / Node.js
- PHP
- Python
curl -G "$ELOFIEL_BASE_URL/api/v1/configuracao" \
-H "X-Api-Key: $ELOFIEL_API_KEY" \
--data-urlencode "cnpjLoja=$CNPJ_LOJA"
const { eloFielFetch, ELOFIEL_CONFIG } = require('./config/elofiel');
async function obterConfiguracao() {
const params = new URLSearchParams({ cnpjLoja: ELOFIEL_CONFIG.cnpjLoja });
return eloFielFetch('GET', `/api/v1/configuracao?${params}`);
}
const config = await obterConfiguracao();
if (config.campanhaAtiva) {
console.log(`Tipo de campanha: ${config.tipoCampanha}`);
console.log(`Checkout cashback: ${config.permiteCheckoutCashbackNaVenda}`);
}
<?php
require_once 'config/elofiel.php';
function obterConfiguracao(): array {
$params = http_build_query(['cnpjLoja' => CNPJ_LOJA]);
return eloFielRequest('GET', '/api/v1/configuracao?' . $params);
}
$config = obterConfiguracao();
if ($config['campanhaAtiva']) {
echo "Campanha: {$config['tipoCampanha']}\n";
}
from urllib.parse import urlencode
from config.elofiel import elofiel_request, CNPJ_LOJA
def obter_configuracao() -> dict:
params = urlencode({'cnpjLoja': CNPJ_LOJA})
return elofiel_request('GET', f'/api/v1/configuracao?{params}')
config = obter_configuracao()
if config['campanhaAtiva']:
print(f"Campanha: {config['tipoCampanha']}")
Registrar Venda
- cURL
- JavaScript / Node.js
- PHP
- Python
curl -X POST "$ELOFIEL_BASE_URL/api/v1/venda" \
-H "Content-Type: application/json" \
-H "X-Api-Key: $ELOFIEL_API_KEY" \
-d "{
\"cnpjLoja\": \"$CNPJ_LOJA\",
\"cpfCliente\": \"123.456.789-09\",
\"valorVenda\": 150.00,
\"documentoExterno\": \"PDV-001234\",
\"observacao\": null
}"
const { eloFielFetch, ELOFIEL_CONFIG } = require('./config/elofiel');
async function registrarVenda(cpfCliente, valorVenda, numeroCupom) {
return eloFielFetch('POST', '/api/v1/venda', {
cnpjLoja: ELOFIEL_CONFIG.cnpjLoja,
cpfCliente,
valorVenda,
documentoExterno: numeroCupom,
observacao: null,
});
}
// Uso:
const venda = await registrarVenda('123.456.789-09', 150.00, 'PDV-001234');
// Issue #3 — itera sobre beneficiosAplicados (1 ou 2 entries)
for (const b of venda.beneficiosAplicados) {
console.log(`${b.campanhaDescricao}: ` +
(b.tipoBeneficio === 'Cashback'
? `R$ ${b.cashbackCreditado} (${b.statusBeneficio})`
: `${b.pontosCreditados} pontos`));
}
console.log(`Total cashback: R$ ${venda.cashbackCreditado} / Total pontos: ${venda.pontosCreditados}`);
console.log(`Saldo atual: R$ ${venda.saldoAtual.saldoCashback}`);
<?php
require_once 'config/elofiel.php';
function registrarVenda(string $cpf, float $valor, string $cupom): array {
return eloFielRequest('POST', '/api/v1/venda', [
'cnpjLoja' => CNPJ_LOJA,
'cpfCliente' => $cpf,
'valorVenda' => $valor,
'documentoExterno' => $cupom,
'observacao' => null,
]);
}
$venda = registrarVenda('123.456.789-09', 150.00, 'PDV-001234');
// Issue #3 — itera sobre beneficiosAplicados (1 ou 2 entries)
foreach ($venda['beneficiosAplicados'] as $b) {
$valor = $b['tipoBeneficio'] === 'Cashback'
? 'R$ ' . number_format($b['cashbackCreditado'], 2, ',', '.')
: $b['pontosCreditados'] . ' pontos';
echo "{$b['campanhaDescricao']}: $valor ({$b['statusBeneficio']})\n";
}
echo "Total cashback: R$ {$venda['cashbackCreditado']} | Total pontos: {$venda['pontosCreditados']}\n";
from config.elofiel import elofiel_request, CNPJ_LOJA
def registrar_venda(cpf_cliente: str, valor_venda: float, numero_cupom: str) -> dict:
return elofiel_request('POST', '/api/v1/venda', {
'cnpjLoja': CNPJ_LOJA,
'cpfCliente': cpf_cliente,
'valorVenda': valor_venda,
'documentoExterno': numero_cupom,
'observacao': None,
})
# Uso:
venda = registrar_venda('123.456.789-09', 150.00, 'PDV-001234')
# Issue #3 — itera sobre beneficiosAplicados (1 ou 2 entries)
for b in venda['beneficiosAplicados']:
if b['tipoBeneficio'] == 'Cashback':
valor = f"R$ {b['cashbackCreditado']:.2f}"
else:
valor = f"{b['pontosCreditados']} pontos"
print(f"{b['campanhaDescricao']}: {valor} ({b['statusBeneficio']})")
print(f"Total cashback: R$ {venda['cashbackCreditado']} | Total pontos: {venda['pontosCreditados']}")
Consultar Saldo
- cURL
- JavaScript / Node.js
- PHP
- Python
curl -G "$ELOFIEL_BASE_URL/api/v1/resgate/saldo" \
-H "X-Api-Key: $ELOFIEL_API_KEY" \
--data-urlencode "cnpjLoja=$CNPJ_LOJA" \
--data-urlencode "cpfCliente=123.456.789-09"
const { eloFielFetch, ELOFIEL_CONFIG } = require('./config/elofiel');
async function consultarSaldo(cpfCliente) {
const params = new URLSearchParams({
cnpjLoja: ELOFIEL_CONFIG.cnpjLoja,
cpfCliente,
});
return eloFielFetch('GET', `/api/v1/resgate/saldo?${params}`);
}
// Uso:
const saldo = await consultarSaldo('123.456.789-09');
console.log(`Disponível: R$ ${saldo.saldoCashback}`);
console.log(`Pendente: R$ ${saldo.saldoPendente}`);
console.log(`Pontos: ${saldo.saldoPontos}`);
<?php
require_once 'config/elofiel.php';
function consultarSaldo(string $cpf): array {
$params = http_build_query([
'cnpjLoja' => CNPJ_LOJA,
'cpfCliente' => $cpf,
]);
return eloFielRequest('GET', '/api/v1/resgate/saldo?' . $params);
}
$saldo = consultarSaldo('123.456.789-09');
echo "Disponível: R$ {$saldo['saldoCashback']}\n";
echo "Pendente: R$ {$saldo['saldoPendente']}\n";
from urllib.parse import urlencode
from config.elofiel import elofiel_request, CNPJ_LOJA
def consultar_saldo(cpf_cliente: str) -> dict:
params = urlencode({
'cnpjLoja': CNPJ_LOJA,
'cpfCliente': cpf_cliente,
})
return elofiel_request('GET', f'/api/v1/resgate/saldo?{params}')
# Uso:
saldo = consultar_saldo('123.456.789-09')
print(f"Disponível: R$ {saldo['saldoCashback']}")
print(f"Pendente: R$ {saldo['saldoPendente']}")
Realizar Resgate
- cURL
- JavaScript / Node.js
- PHP
- Python
# Resgate parcial de R$ 10,00
curl -X POST "$ELOFIEL_BASE_URL/api/v1/resgate" \
-H "Content-Type: application/json" \
-H "X-Api-Key: $ELOFIEL_API_KEY" \
-d "{
\"cnpjLoja\": \"$CNPJ_LOJA\",
\"cpfCliente\": \"123.456.789-09\",
\"tipoBeneficio\": \"Cashback\",
\"valorResgate\": 10.00,
\"pontosResgate\": null,
\"documentoExterno\": \"PDV-001235\",
\"observacao\": null
}"
const { eloFielFetch, ELOFIEL_CONFIG } = require('./config/elofiel');
async function realizarResgate(cpfCliente, tipoBeneficio, valorResgate = null, pontosResgate = null) {
return eloFielFetch('POST', '/api/v1/resgate', {
cnpjLoja: ELOFIEL_CONFIG.cnpjLoja,
cpfCliente,
tipoBeneficio,
valorResgate,
pontosResgate,
documentoExterno: `RES-${Date.now()}`,
observacao: null,
});
}
// Resgate parcial de cashback (R$ 10,00):
const resgate = await realizarResgate('123.456.789-09', 'Cashback', 10.00);
// Resgate total de cashback (null = tudo):
// const resgate = await realizarResgate('123.456.789-09', 'Cashback', null);
// Resgate de 50 pontos:
// const resgate = await realizarResgate('123.456.789-09', 'Pontos', null, 50);
console.log(`Resgatado: R$ ${resgate.cashbackResgatado}`);
console.log(`Saldo restante: R$ ${resgate.saldoAtual.saldoCashback}`);
<?php
require_once 'config/elofiel.php';
function realizarResgate(
string $cpf,
string $tipo,
?float $valorCashback = null,
?int $pontos = null
): array {
return eloFielRequest('POST', '/api/v1/resgate', [
'cnpjLoja' => CNPJ_LOJA,
'cpfCliente' => $cpf,
'tipoBeneficio' => $tipo,
'valorResgate' => $valorCashback,
'pontosResgate' => $pontos,
'documentoExterno' => 'RES-' . time(),
'observacao' => null,
]);
}
// Resgate de R$ 10,00:
$resgate = realizarResgate('123.456.789-09', 'Cashback', 10.00);
echo "Resgatado: R$ {$resgate['cashbackResgatado']}\n";
echo "Saldo restante: R$ {$resgate['saldoAtual']['saldoCashback']}\n";
import time
from config.elofiel import elofiel_request, CNPJ_LOJA
def realizar_resgate(
cpf_cliente: str,
tipo_beneficio: str,
valor_resgate: float = None,
pontos_resgate: int = None,
) -> dict:
return elofiel_request('POST', '/api/v1/resgate', {
'cnpjLoja': CNPJ_LOJA,
'cpfCliente': cpf_cliente,
'tipoBeneficio': tipo_beneficio,
'valorResgate': valor_resgate,
'pontosResgate': pontos_resgate,
'documentoExterno': f'RES-{int(time.time())}',
'observacao': None,
})
# Resgate de R$ 10,00:
resgate = realizar_resgate('123.456.789-09', 'Cashback', valor_resgate=10.00)
print(f"Resgatado: R$ {resgate['cashbackResgatado']}")
print(f"Saldo restante: R$ {resgate['saldoAtual']['saldoCashback']}")