docs

Gerar token de acesso JWT

POST /api/auth/token

POST https://api.fypay.me/api/auth/token

Autentique com o certificado de cliente X.509 + credenciais (clientId/clientSecret) e receba um token JWT. A validade do token vem no campo expires_in (em segundos): use esse valor para renovar o token antes de expirar, sem assumir um tempo fixo.

Autenticação (mTLS)

Esta rota exige mTLS: o certificado de cliente emitido pela FyPay é apresentado no handshake TLS, não em um header HTTP. Use o mecanismo nativo de certificado de cliente da sua biblioteca HTTP (por exemplo, curl --cert client.crt --key client.key).

  • O certificado é PEM, RSA 2048, válido por 2 anos e vinculado à sua conta.
  • O mTLS é exigido somente nesta rota. As demais rotas usam Authorization: Bearer <token>, sem certificado.

Não envie o certificado em headers HTTP: esse modelo não é aceito. Sem o certificado no handshake, a API responde 400 com PUB_CERT_HEADER_MISSING.

Request Body

CampoTipoObrigatórioDescrição
clientIdstring (UUID v4)SimClient ID gerado no painel (https://banking.fypay.me), em Configurações → Credenciais
clientSecretstringSimClient secret gerado junto com o clientId. É exibido uma única vez no painel. Não pode ser vazio
{
  "clientId": "6967c0a0-3566-48d0-8c13-717038b52279",
  "clientSecret": "SEU_CLIENT_SECRET"
}

Exemplo com cURL

curl -X POST https://api.fypay.me/api/auth/token \
  --cert ./client.crt \
  --key ./client.key \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "SEU_CLIENT_ID",
    "clientSecret": "SEU_CLIENT_SECRET"
  }'

Exemplos de Código

const https = require('https');
const fs = require('fs');
const axios = require('axios');

const httpsAgent = new https.Agent({
  cert: fs.readFileSync('./client.crt'),
  key: fs.readFileSync('./client.key'),
});

const response = await axios.post(
  'https://api.fypay.me/api/auth/token',
  {
    clientId: process.env.FYPAY_CLIENT_ID,
    clientSecret: process.env.FYPAY_CLIENT_SECRET,
  },
  { httpsAgent },
);

console.log('Token:', response.data.access_token);
console.log('Expira em:', response.data.expires_in, 'segundos');
import os
import requests

response = requests.post(
    'https://api.fypay.me/api/auth/token',
    json={
        'clientId': os.environ['FYPAY_CLIENT_ID'],
        'clientSecret': os.environ['FYPAY_CLIENT_SECRET'],
    },
    cert=('client.crt', 'client.key'),
)
response.raise_for_status()

data = response.json()
print(f"Token: {data['access_token']}")
print(f"Expira em: {data['expires_in']} segundos")
<?php
$ch = curl_init('https://api.fypay.me/api/auth/token');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSLCERT => __DIR__ . '/client.crt',
    CURLOPT_SSLKEY => __DIR__ . '/client.key',
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode([
        'clientId' => getenv('FYPAY_CLIENT_ID'),
        'clientSecret' => getenv('FYPAY_CLIENT_SECRET'),
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo "Token: " . $data['access_token'] . "\n";
echo "Expira em: " . $data['expires_in'] . " segundos\n";
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;

var certificate = X509Certificate2.CreateFromPemFile("client.crt", "client.key");

var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);

using var client = new HttpClient(handler);
var response = await client.PostAsJsonAsync(
    "https://api.fypay.me/api/auth/token",
    new
    {
        clientId = Environment.GetEnvironmentVariable("FYPAY_CLIENT_ID"),
        clientSecret = Environment.GetEnvironmentVariable("FYPAY_CLIENT_SECRET"),
    });

response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
package main

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
	if err != nil {
		panic(err)
	}

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
		},
	}

	body, _ := json.Marshal(map[string]string{
		"clientId":     os.Getenv("FYPAY_CLIENT_ID"),
		"clientSecret": os.Getenv("FYPAY_CLIENT_SECRET"),
	})

	resp, err := client.Post("https://api.fypay.me/api/auth/token", "application/json", bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	var data map[string]any
	json.NewDecoder(resp.Body).Decode(&data)
	fmt.Println("Token:", data["access_token"])
	fmt.Println("Expira em:", data["expires_in"], "segundos")
}
import java.io.FileInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

char[] password = System.getenv("FYPAY_KEYSTORE_PASSWORD").toCharArray();

KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (FileInputStream in = new FileInputStream("client.p12")) {
    keyStore.load(in, password);
}

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, password);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);

String body = String.format(
    "{\"clientId\":\"%s\",\"clientSecret\":\"%s\"}",
    System.getenv("FYPAY_CLIENT_ID"),
    System.getenv("FYPAY_CLIENT_SECRET")
);

HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.fypay.me/api/auth/token"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

A FyPay entrega o certificado em PEM (client.crt + client.key). Se a sua plataforma exige um arquivo .pfx/.p12 (comum em Java e em alguns ambientes Windows/.NET), converta localmente:

openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12

A conversão é feita na sua máquina; a FyPay não fornece PFX.

Response (201)

CampoTipoDescrição
access_tokenstringToken JWT para o header Authorization: Bearer <token>
token_typestringSempre Bearer
expires_innumberValidade do token em segundos. Renove antes de expirar com base neste valor
scopestringEscopo do token
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 600,
  "scope": "email profile"
}

Erros

StatusCódigoDescrição
400PUB_CERT_HEADER_MISSINGCertificado de cliente não apresentado no handshake TLS
400PUB_CERT_MALFORMED_PEMCertificado em formato PEM inválido
400PUB_REQUEST_BODY_INVALIDBody inválido (ex.: clientId não é UUID v4, clientSecret vazio, campos extras). Os campos com problema vêm em details.violations
401PUB_INVALID_CREDENTIALSclientId/clientSecret inválidos
401PUB_CERT_NOT_VERIFIEDCertificado não pôde ser verificado na conexão
401PUB_CERT_NOT_REGISTEREDCertificado não cadastrado
401PUB_CERT_EXPIREDCertificado expirado
401PUB_CERT_NOT_YET_VALIDCertificado ainda não está no período de validade
403PUB_CERT_NOT_AUTHORIZED_FOR_ACCOUNTCertificado não está vinculado à conta das credenciais
502PUB_AUTH_UPSTREAM_ERRORErro inesperado no serviço de autenticação
503PUB_AUTH_UPSTREAM_UNAVAILABLEServiço de autenticação temporariamente indisponível. Tente novamente
{
  "statusCode": 401,
  "timestamp": "2026-04-17T15:24:28.809Z",
  "path": "/api/auth/token",
  "method": "POST",
  "code": "PUB_INVALID_CREDENTIALS",
  "message": "Invalid credentials provided",
  "userMessage": "Invalid credentials.",
  "errorId": "75d7999d6d7656b737e83435ced86ec6"
}

Para um guia completo de autenticação com padrões de renovação de token, veja Guia de Autenticação.

Nesta página