Vou ajudar você a criar um sistema web para integração com a API Pix do Santander. Vou detalhar a estrutura e os passos necessários.
Estrutura do Projeto
santander-pix/
├── backend/
│ ├── app/
│ │ ├── __init__.py
│ │ ├── config.py
│ │ ├── routes.py
│ │ └── services/
│ │ └── santander_service.py
│ ├── requirements.txt
│ └── run.py
└── frontend/
├── static/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── main.js
└── templates/
└── index.html
Passo a Passo
- Primeiro, crie o ambiente virtual e instale as dependências:
python -m venv venv
source venv/bin/activate # Linux/Mac
# ou
venv\Scripts\activate # Windows
pip install flask requests python-dotenv
- Crie o arquivo
requirements.txt:
Flask==2.0.1
requests==2.26.0
python-dotenv==0.19.0
- Configure o arquivo
config.py:
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
SANTANDER_CLIENT_ID = os.getenv('SANTANDER_CLIENT_ID')
SANTANDER_CLIENT_SECRET = os.getenv('SANTANDER_CLIENT_SECRET')
SANTANDER_CERT_PATH = os.getenv('SANTANDER_CERT_PATH')
SANTANDER_API_URL = 'https://api.santander.com.br/sandbox' # URL do sandbox
- Crie o arquivo
santander_service.py:
import requests
from app.config import Config
class SantanderService:
def __init__(self):
self.config = Config()
self.token = None
def get_access_token(self):
url = f"{self.config.SANTANDER_API_URL}/oauth/token"
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials",
"client_id": self.config.SANTANDER_CLIENT_ID,
"client_secret": self.config.SANTANDER_CLIENT_SECRET
}
response = requests.post(url, headers=headers, data=data)
self.token = response.json()["access_token"]
return self.token
def create_pix_charge(self, amount, description):
url = f"{self.config.SANTANDER_API_URL}/pix/v1/charges"
headers = {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
payload = {
"amount": amount,
"description": description,
"expiration": 3600
}
response = requests.post(url, headers=headers, json=payload)
return response.json()
- Configure as rotas em
routes.py:
from flask import Blueprint, jsonify, request
from app.services.santander_service import SantanderService
bp = Blueprint('main', __name__)
santander_service = SantanderService()
@bp.route('/create-charge', methods=['POST'])
def create_charge():
data = request.json
amount = data.get('amount')
description = data.get('description')
try:
santander_service.get_access_token()
charge = santander_service.create_pix_charge(amount, description)
return jsonify(charge)
except Exception as e:
return jsonify({"error": str(e)}), 400
- Crie o arquivo
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Pagamento PIX</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<div class="container">
<h1>Pagamento via PIX</h1>
<form id="pixForm">
<div class="form-group">
<label>Valor:</label>
<input type="number" id="amount" step="0.01" required>
</div>
<div class="form-group">
<label>Descrição:</label>
<input type="text" id="description" required>
</div>
<button type="submit">Gerar QR Code</button>
</form>
<div id="qrcode-container">
<img id="qrcode" src="" alt="QR Code PIX" style="display: none;">
<p id="pixCopiaeCola"></p>
</div>
</div>
<script src="/static/js/main.js"></script>
</body>
</html>
- Crie o arquivo
style.css:
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background-color: #e31837;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
#qrcode-container {
margin-top: 20px;
text-align: center;
}
- Crie o arquivo
main.js:
document.getElementById('pixForm').addEventListener('submit', async (e) => {
e.preventDefault();
const amount = document.getElementById('amount').value;
const description = document.getElementById('description').value;
try {
const response = await fetch('/create-charge', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ amount, description })
});
const data = await response.json();
if (data.qrcode) {
const qrcodeImg = document.getElementById('qrcode');
qrcodeImg.src = `data:image/png;base64,${data.qrcode}`;
qrcodeImg.style.display = 'block';
document.getElementById('pixCopiaeCola').textContent = data.pixCopiaeCola;
}
} catch (error) {
console.error('Erro:', error);
alert('Erro ao gerar o QR Code');
}
});
- Crie o arquivo
.env na raiz do projeto:
SANTANDER_CLIENT_ID=seu_client_id
SANTANDER_CLIENT_SECRET=seu_client_secret
SANTANDER_CERT_PATH=caminho_do_certificado
- Para rodar o projeto:
python run.py
Observações Importantes:
-
Você precisará se cadastrar no portal Santander Developers e obter as credenciais (Client ID e Client Secret)
-
Configure o certificado digital fornecido pelo Santander
-
Teste primeiro no ambiente sandbox antes de ir para produção
-
Implemente tratamento de erros adequado
-
Adicione validações de segurança
-
Implemente o webhook para receber as confirmações de pagamento
Para usar o sandbox do Santander:
- Acesse o portal Santander Developers
- Crie uma conta de desenvolvedor
- Crie uma aplicação
- Obtenha as credenciais do sandbox
- Configure o certificado digital
- Teste as chamadas usando o Postman antes de implementar no código
Você precisará implementar também o endpoint de webhook para receber as confirmações de pagamento do Santander. Isso permitirá que seu sistema seja notificado quando um PIX for recebido.
Quer que eu detalhe alguma parte específica do código ou explique melhor algum dos passos?