SDKs oficiais estão em desenvolvimento. Enquanto isso, use os exemplos abaixo — são simples, prontos para copiar e usar direto no seu projeto.
URL Base
Copy
https://upay-sistema-api.onrender.com/api/v1
Copy
Authorization: Bearer SUA_API_KEY
JavaScript / TypeScript
Exemplo direto com fetch
Copy
const BASE_URL = 'https://upay-sistema-api.onrender.com/api/v1';
async function upay(method, path, body) {
const res = await fetch(`${BASE_URL}${path}`, {
method,
headers: {
'Authorization': `Bearer ${process.env.UPAY_API_KEY}`,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json();
if (!res.ok) throw new Error(data.message ?? `HTTP ${res.status}`);
return data;
}
// Criar link de pagamento
const link = await upay('POST', '/payment-links', {
title: 'Produto Premium',
amount: 9900, // R$ 99,00 em centavos
description: 'Acesso vitalício',
});
console.log('Checkout:', link.data.url);
// Listar transações
const { data } = await upay('GET', '/transactions?page=1&limit=20');
Client reutilizável (TypeScript)
Copie e cole no seu projeto:Copy
// upay-client.ts
const BASE_URL = 'https://upay-sistema-api.onrender.com/api/v1';
export class UpayClient {
constructor(private apiKey: string) {}
private async req<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${BASE_URL}${path}`, {
method,
headers: {
Authorization: `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json();
if (!res.ok) throw new Error(data.message ?? `HTTP ${res.status}`);
return data;
}
// Links de pagamento
createPaymentLink(title: string, amount: number, extra?: object) {
return this.req('POST', '/payment-links', { title, amount, ...extra });
}
listPaymentLinks(page = 1, limit = 20) {
return this.req('GET', `/payment-links?page=${page}&limit=${limit}`);
}
getPaymentLink(id: string) {
return this.req('GET', `/payment-links/${id}`);
}
// Transações
listTransactions(page = 1, limit = 20) {
return this.req('GET', `/transactions?page=${page}&limit=${limit}`);
}
getTransaction(id: string) {
return this.req('GET', `/transactions/${id}`);
}
// Produtos
createProduct(name: string, price: number, extra?: object) {
return this.req('POST', '/products', { name, price, ...extra });
}
listProducts(page = 1, limit = 20) {
return this.req('GET', `/products?page=${page}&limit=${limit}`);
}
}
Copy
import { UpayClient } from './upay-client';
const upay = new UpayClient(process.env.UPAY_API_KEY!);
const link = await upay.createPaymentLink('Curso Node.js', 19900, {
description: 'Acesso vitalício ao curso',
});
console.log('Checkout:', link.data.url);
const { data: transactions } = await upay.listTransactions();
console.log(`${transactions.length} transações encontradas`);
Python
Exemplo direto com requests
Copy
import requests, os
BASE_URL = 'https://upay-sistema-api.onrender.com/api/v1'
HEADERS = {
'Authorization': f'Bearer {os.getenv("UPAY_API_KEY")}',
'Content-Type': 'application/json',
}
def upay(method, path, **kwargs):
r = requests.request(method, f'{BASE_URL}{path}', headers=HEADERS, **kwargs)
r.raise_for_status()
return r.json()
# Criar link de pagamento
link = upay('POST', '/payment-links', json={
'title': 'Produto Premium',
'amount': 9900,
'description': 'Acesso vitalício',
})
print('Checkout:', link['data']['url'])
# Listar transações
result = upay('GET', '/transactions', params={'page': 1, 'limit': 20})
Client reutilizável
Copie e cole no seu projeto:Copy
# upay_client.py
import os
import requests
class UpayClient:
BASE_URL = 'https://upay-sistema-api.onrender.com/api/v1'
def __init__(self, api_key: str):
self._session = requests.Session()
self._session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
})
def _req(self, method: str, path: str, **kwargs):
r = self._session.request(method, f'{self.BASE_URL}{path}', **kwargs)
r.raise_for_status()
return r.json()
# Links de pagamento
def create_payment_link(self, title: str, amount: int, **kwargs):
return self._req('POST', '/payment-links', json={'title': title, 'amount': amount, **kwargs})
def list_payment_links(self, page=1, limit=20):
return self._req('GET', '/payment-links', params={'page': page, 'limit': limit})
def get_payment_link(self, id: str):
return self._req('GET', f'/payment-links/{id}')
# Transações
def list_transactions(self, page=1, limit=20):
return self._req('GET', '/transactions', params={'page': page, 'limit': limit})
def get_transaction(self, id: str):
return self._req('GET', f'/transactions/{id}')
# Produtos
def create_product(self, name: str, price: int, **kwargs):
return self._req('POST', '/products', json={'name': name, 'price': price, **kwargs})
def list_products(self, page=1, limit=20):
return self._req('GET', '/products', params={'page': page, 'limit': limit})
Copy
from upay_client import UpayClient
upay = UpayClient(os.getenv('UPAY_API_KEY'))
link = upay.create_payment_link(
'Curso Python',
9900,
description='Acesso vitalício',
)
print('Checkout:', link['data']['url'])
result = upay.list_transactions(page=1)
print(f"{len(result['data'])} transações encontradas")
PHP
Copie e cole no seu projeto:Copy
<?php
// UpayClient.php
class UpayClient
{
private string $baseUrl = 'https://upay-sistema-api.onrender.com/api/v1';
public function __construct(private string $apiKey) {}
private function request(string $method, string $path, ?array $body = null): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->baseUrl . $path,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer {$this->apiKey}",
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => $body ? json_encode($body) : null,
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if ($status >= 400) {
throw new RuntimeException($data['message'] ?? "HTTP $status");
}
return $data;
}
// Links de pagamento
public function createPaymentLink(string $title, int $amount, array $extra = []): array
{
return $this->request('POST', '/payment-links', array_merge(
['title' => $title, 'amount' => $amount], $extra
));
}
public function listPaymentLinks(int $page = 1, int $limit = 20): array
{
return $this->request('GET', "/payment-links?page=$page&limit=$limit");
}
// Transações
public function listTransactions(int $page = 1, int $limit = 20): array
{
return $this->request('GET', "/transactions?page=$page&limit=$limit");
}
// Produtos
public function createProduct(string $name, int $price, array $extra = []): array
{
return $this->request('POST', '/products', array_merge(
['name' => $name, 'price' => $price], $extra
));
}
}
Copy
<?php
require 'UpayClient.php';
$upay = new UpayClient($_ENV['UPAY_API_KEY']);
$link = $upay->createPaymentLink('Produto Premium', 9900, [
'description' => 'Acesso vitalício',
]);
echo 'Checkout: ' . $link['data']['url'] . "\n";
$result = $upay->listTransactions();
echo count($result['data']) . " transações encontradas\n";
Webhooks
A Upay envia eventos via webhook com assinatura HMAC-SHA256 no headerx-signature. Sempre valide a assinatura antes de processar o evento.
Copy
const crypto = require('crypto');
// Express — use express.raw() para preservar o body original
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-signature'];
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
if (signature !== expected) {
return res.status(401).json({ error: 'Assinatura inválida' });
}
const event = JSON.parse(req.body.toString());
console.log('Evento recebido:', event.event);
res.json({ received: true });
});
O
WEBHOOK_SECRET é configurado na seção Webhooks do Dashboard. Use sempre variáveis de ambiente para armazená-lo.Variáveis de ambiente
Copy
UPAY_API_KEY=sua_api_key_aqui
UPAY_WEBHOOK_SECRET=seu_webhook_secret_aqui
Nunca commite sua API Key ou Webhook Secret no código. Adicione
.env ao .gitignore.Obter API Key
- Acesse o Dashboard Upay
- Vá em Configurações → Credenciais de API
- Clique em Criar Nova API Key e selecione as permissões necessárias
- Copie e guarde em local seguro — ela não será exibida novamente

