ZypfyDocs Acessar painel
Guia de integração

Autenticação

A Zypfy usa autenticação Bearer com JWT (JSON Web Token). O fluxo é:

  1. Você faz POST /api/auth/login com client_id + client_secret.
  2. A Zypfy devolve um token válido por 1 hora (3600 segundos).
  3. Você envia o token no header Authorization: Bearer SEU_TOKEN em todas as chamadas subsequentes.

Endpoint

código
POST https://api.zypfybr.com/api/auth/login

Headers: Content-Type: application/json (sem auth).

Body:

json
{
  "client_id": "minhaloja_ABCD1234",
  "client_secret": "seu_client_secret_de_100_caracteres"
}

Resposta 200 OK:

json
{
  "message": "Authentication successful.",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": 42,
    "name": "Minha Loja",
    "email": "[email protected]",
    "verification_docs": 1
  }
}

Use o token nas chamadas seguintes:

código
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Cache de token (obrigatório)

O token tem validade de 1 hora. Sua integração deve cachear o token e reutilizá-lo até ele estar prestes a expirar. Não chame /api/auth/login a cada requisição — se fizer isso, você será bloqueado pelo rate limit.

Padrão recomendado

Exemplo: cache em Node.js (memória compartilhada por worker)

javascript
import axios from 'axios';

let cachedToken = null;
let cachedUntil = 0;

async function getToken() {
  const now = Date.now();
  if (cachedToken && now < cachedUntil) return cachedToken;

  const { data } = await axios.post('https://api.zypfybr.com/api/auth/login', {
    client_id: process.env.ZYPFY_CLIENT_ID,
    client_secret: process.env.ZYPFY_CLIENT_SECRET,
  });

  cachedToken = data.token;
  cachedUntil = now + 55 * 60 * 1000; // 55 minutos
  return cachedToken;
}

Exemplo: cache compartilhado em Redis (múltiplos workers)

javascript
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);

async function getToken() {
  let token = await redis.get('zypfy:token');
  if (token) return token;

  const { data } = await axios.post('https://api.zypfybr.com/api/auth/login', {
    client_id: process.env.ZYPFY_CLIENT_ID,
    client_secret: process.env.ZYPFY_CLIENT_SECRET,
  });

  await redis.set('zypfy:token', data.token, 'EX', 3300); // 55 minutos em segundos
  return data.token;
}

Exemplo em PHP (Laravel com Cache facade)

php
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

function zypfyToken(): string {
    return Cache::remember('zypfy_token', now()->addMinutes(55), function () {
        $resp = Http::post('https://api.zypfybr.com/api/auth/login', [
            'client_id'     => env('ZYPFY_CLIENT_ID'),
            'client_secret' => env('ZYPFY_CLIENT_SECRET'),
        ]);
        return $resp->json('token');
    });
}

Exemplo em Python

python
import os, time, requests

_cached = {"token": None, "until": 0}

def zypfy_token():
    now = time.time()
    if _cached["token"] and now < _cached["until"]:
        return _cached["token"]
    resp = requests.post(
        "https://api.zypfybr.com/api/auth/login",
        json={
            "client_id":     os.environ["ZYPFY_CLIENT_ID"],
            "client_secret": os.environ["ZYPFY_CLIENT_SECRET"],
        },
        timeout=10,
    )
    resp.raise_for_status()
    data = resp.json()
    _cached["token"] = data["token"]
    _cached["until"] = now + 55 * 60
    return data["token"]

Exemplo em cURL

bash
# Gerar token (uma vez por hora)
curl -X POST https://api.zypfybr.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"client_id":"...","client_secret":"..."}'

# Usar token em chamadas subsequentes
curl https://api.zypfybr.com/api/accounts/balance \
  -H "Authorization: Bearer eyJhbGc..."

Rate limit

O endpoint /api/auth/login tem rate limit de 25 tentativas por IP a cada 15 minutos. Exceder retorna:

http
HTTP/1.1 429 Too Many Requests
Content-Type: application/json

{
  "message": "Too many login attempts. Try again in 15 minutes."
}

Headers RateLimit-Limit, RateLimit-Remaining e RateLimit-Reset ajudam a monitorar quantas chamadas você ainda tem.

Segurança das credenciais