Guia de Integração
Comece a aceitar pagamentos M-Pesa, e-Mola e mKesh em minutos.
Como funciona
1
Crie a conta
Registe-se e obtenha a sua API Key
2
Integre a API
Envie pagamentos via REST API
3
Receba
Webhooks notificam o resultado
1
Criar conta e obter API Key
Registe-se em /register, depois vá ao Dashboard e gere uma API Key em API Keys.
# Registar
curl -X POST https://a.bridgepay.site/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "dev@empresa.com",
"password": "senha_segura",
"business_name": "Minha Empresa",
"account_type": "managed"
}'
# Login para obter JWT
curl -X POST https://a.bridgepay.site/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "dev@empresa.com", "password": "senha_segura"}'
# Gerar API Key (usar JWT do login)
curl -X POST https://a.bridgepay.site/api/v1/auth/api-keys \
-H "Authorization: Bearer SEU_JWT" \
-H "Content-Type: application/json" \
-d '{"label": "Produção"}'
# Resposta: { "key": "bp_live_abc123..." } — guardar!2
Processar um pagamento
Use a API Key para iniciar cobranças. O cliente recebe um push USSD no telemóvel para confirmar.
curl -X POST https://a.bridgepay.site/api/v1/payments \
-H "Authorization: Bearer bp_live_abc123..." \
-H "Content-Type: application/json" \
-d '{
"amount": 500.00,
"mobile": "841234567",
"method": "mpesa",
"reference": "ORDER-789",
"callback_url": "https://meusite.com/api/bridgepay-webhook"
}'
# Resposta:
# {
# "id": "uuid-da-transaccao",
# "status": "processing",
# "amount": 500.00,
# "fee": 7.50,
# ...
# }Métodos disponíveis:
mpesa— Vodacom M-Pesaemola— Movitel e-Molamkesh— TMCel mKesh
3
Receber webhook de confirmação
Configure o webhook no Dashboard em Configurações. Quando o pagamento for concluído (ou falhar), o BridgePay envia um POST ao seu endpoint.
// Payload recebido no seu webhook:
POST https://meusite.com/api/bridgepay-webhook
Headers:
Content-Type: application/json
X-BridgePay-Signature: sha256=abc123...
Body:
{
"event": "payment.completed",
"data": {
"transaction_id": "uuid",
"bridgepay_ref": "BP-abc123",
"amount": 500.00,
"fee": 7.50,
"net_amount": 492.50,
"status": "completed",
"method": "mpesa",
"reference": "ORDER-789",
"completed_at": "2026-01-01T00:05:00Z"
},
"timestamp": "2026-01-01T00:05:00Z"
}# Validar assinatura (Python)
import hmac, hashlib
def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
expected = hmac.new(
secret.encode(), payload, hashlib.sha256
).hexdigest()
return hmac.compare_digest(f"sha256={expected}", signature)
# No seu endpoint:
# sig = request.headers["X-BridgePay-Signature"]
# valid = verify_signature(request.body, sig, "seu_webhook_secret")4
Consultar estado do pagamento
Além do webhook, pode consultar o estado a qualquer momento:
# Por ID do pagamento
curl https://a.bridgepay.site/api/v1/payments/{payment_id} \
-H "Authorization: Bearer bp_live_abc123..."
# Listar todos os pagamentos
curl "https://a.bridgepay.site/api/v1/payments?status=completed&limit=10" \
-H "Authorization: Bearer bp_live_abc123..."
# Estatísticas
curl https://a.bridgepay.site/api/v1/transactions/stats \
-H "Authorization: Bearer bp_live_abc123..."5
Alternativa: Checkout Links
Sem escrever código? Crie links de pagamento personalizados e partilhe com os clientes via WhatsApp, SMS, ou email.
# Criar checkout personalizado
curl -X POST https://a.bridgepay.site/api/v1/checkouts \
-H "Authorization: Bearer bp_live_abc123..." \
-H "Content-Type: application/json" \
-d '{
"amount": 1500.00,
"description": "Encomenda #456",
"brand_name": "Minha Loja",
"brand_color": "#FF6B35",
"allowed_methods": "mpesa,emola",
"expires_minutes": 60
}'
# Resposta:
# {
# "checkout_url": "https://dev.bridgepay.site/pay/abc123xyz",
# "status": "open",
# ...
# }
# Partilhe o checkout_url com o cliente!Exemplos de Integração
Python (requests)
import requests
API_KEY = "bp_live_abc123..."
BASE_URL = "https://a.bridgepay.site/api/v1"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
# Criar pagamento
resp = requests.post(f"{BASE_URL}/payments", headers=headers, json={
"amount": 500.00,
"mobile": "841234567",
"method": "mpesa",
"reference": "ORDER-789",
})
payment = resp.json()
print(f"Pagamento {payment['id']} — status: {payment['status']}")
# Verificar estado
resp = requests.get(f"{BASE_URL}/payments/{payment['id']}", headers=headers)
print(resp.json())Node.js (axios)
const axios = require("axios");
const api = axios.create({
baseURL: "https://a.bridgepay.site/api/v1",
headers: { Authorization: "Bearer bp_live_abc123..." },
});
// Criar pagamento
const { data: payment } = await api.post("/payments", {
amount: 500.0,
mobile: "841234567",
method: "mpesa",
reference: "ORDER-789",
});
console.log(`Pagamento ${payment.id} — status: ${payment.status}`);
// Webhook handler (Express)
const crypto = require("crypto");
app.post("/api/bridgepay-webhook", (req, res) => {
const sig = req.headers["x-bridgepay-signature"];
const expected = "sha256=" + crypto
.createHmac("sha256", process.env.WEBHOOK_SECRET)
.update(JSON.stringify(req.body))
.digest("hex");
if (sig !== expected) return res.status(401).send("Invalid signature");
const { event, data } = req.body;
if (event === "payment.completed") {
// Actualizar encomenda no banco de dados
console.log(`Pagamento ${data.reference} completado!`);
}
res.json({ received: true });
});PHP (cURL)
<?php
$api_key = "bp_live_abc123...";
$base_url = "https://a.bridgepay.site/api/v1";
// Criar pagamento
$ch = curl_init("$base_url/payments");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $api_key",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"amount" => 500.00,
"mobile" => "841234567",
"method" => "mpesa",
"reference" => "ORDER-789",
]),
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
echo "Pagamento {$response['id']} — status: {$response['status']}";
// Webhook handler
$payload = file_get_contents("php://input");
$sig = $_SERVER["HTTP_X_BRIDGEPAY_SIGNATURE"];
$expected = "sha256=" . hash_hmac("sha256", $payload, $webhook_secret);
if (!hash_equals($expected, $sig)) {
http_response_code(401);
exit("Invalid signature");
}
$data = json_decode($payload, true);
if ($data["event"] === "payment.completed") {
// Actualizar encomenda
}
echo json_encode(["received" => true]);Boas Práticas
- 1. Sempre valide a assinatura do webhook antes de processar.
- 2. Use
referencepara mapear pagamentos às encomendas no seu sistema. - 3. Guarde a API Key em variáveis de ambiente, nunca no código.
- 4. Implemente retry logic no webhook — responda 200 rapidamente e processe em background.
- 5. Use o
callback_urlpor pagamento se precisar de webhooks diferentes por transacção. - 6. Para integração sem código, use os Checkout Links no dashboard.