Exemplos de código
Token, assinatura e chamadas reais (saldo, extrato e PIX) em bash, Node.js, Python e Go.
Programas completos, do token ao PIX. Cada um faz as mesmas três chamadas — saldo, extrato com filtro e um PIX por chave — e monta os headers de assinatura do mesmo jeito. Todos foram verificados contra o código que valida as assinaturas na API.
O POST /pix/out dos exemplos envia R$ 100,00 de verdade. Para testar só a
assinatura, comente essa chamada ou use
POST /v1/security/signature/verify.
Antes de rodar
Você precisa de uma credencial já fora da carência, com a chave pública cadastrada (Gerar o par de chaves), e de um servidor cujo IP de saída esteja na allowlist.
export CLIENT_ID="..." # client_id da tela de credenciaisexport CLIENT_SECRET="..." # client_secret (exibido uma vez)export TENANT_ID="..." # X-Tenant-Id informado pelo bancoexport ACCOUNT_ID="..." # conta da credencialexport PRIVATE_KEY_FILE="./corpx-signing.key"# Opcionais (estes são os padrões):# export TOKEN_URL="https://auth.api.corpx.com/oauth2/token"# export API_BASE="https://client.api.corpx.com"
Os exemplos calculam o kid a partir da chave privada (SHA-256 do DER da
pública, primeiros 16 bytes). Node, Python e Go também deduzem o alg
(ES256 para EC, PS256 para RSA); no bash, exporte ALG=PS256 se a
chave for RSA.
Três regras valem para todas as linguagens:
- Assine os bytes que você envia. Serialize o JSON uma vez, calcule o hash sobre essa string e mande exatamente ela. Deixar a biblioteca HTTP reserializar o objeto muda espaços e ordem de chaves.
pathcom a query, exatamente como vai na URL. Mesma ordem de parâmetros, mesmo encoding.Idempotency-Keyé da tentativa. Em retry de um POST, reenvie a mesma chave (e assine de novo, com timestamp novo).
bash + curl + openssl
Requer bash (não sh), curl, openssl, xxd e jq. Funciona com
OpenSSL 1.1.1+, OpenSSL 3 e o LibreSSL do macOS.
#!/usr/bin/env bash# Requer: bash, curl, openssl (OpenSSL 1.1.1+/3.x ou LibreSSL), xxd, jq.set -euo pipefailTOKEN_URL="${TOKEN_URL:-https://auth.api.corpx.com/oauth2/token}"API_BASE="${API_BASE:-https://client.api.corpx.com}": "${CLIENT_ID:?}" "${CLIENT_SECRET:?}" "${TENANT_ID:?}" "${ACCOUNT_ID:?}"KEY="${PRIVATE_KEY_FILE:-./corpx-signing.key}"ALG="${ALG:-ES256}" # PS256 se a chave for RSA# kid = primeiros 16 bytes (32 hex) do SHA-256 do DER da chave pública.KID=$(openssl pkey -in "$KEY" -pubout -outform DER | openssl dgst -sha256 -r | cut -c1-32)b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }# O openssl emite ECDSA em DER; a API exige R||S (32 + 32 bytes).der_to_rs() {openssl asn1parse -inform DER | awk -F: '/INTEGER/ {print $NF}' |while read -r h; doh=$(printf '%s' "$h" | sed 's/^0*//')printf '%64s' "$h" | tr ' ' 0done | xxd -r -p}# sign METODO PATH_COM_QUERY CORPO IDEMPOTENCY_KEY -> define TS, SHA e SIGsign() {local method=$1 path=$2 body=$3 idem=$4 canonical protected input sigTS=$(date +%s)SHA=$(printf '%s' "$body" | openssl dgst -sha256 -r | cut -c1-64)canonical=$(printf '%s\n%s\n%s\n%s\n%s' "$method" "$path" "$TS" "$idem" "$SHA")protected=$(printf '{"alg":"%s","kid":"%s"}' "$ALG" "$KID" | b64url)input="$protected.$(printf '%s' "$canonical" | b64url)"if [ "$ALG" = ES256 ]; thensig=$(printf '%s' "$input" | openssl dgst -sha256 -sign "$KEY" | der_to_rs | b64url)elsesig=$(printf '%s' "$input" | openssl dgst -sha256 -sign "$KEY" \-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 | b64url)fiSIG="$protected..$sig"}# 1. Token (reutilize até perto de expires_in)TOKEN=$(curl -sS -X POST "$TOKEN_URL" \-H "Content-Type: application/x-www-form-urlencoded" \--data-urlencode "grant_type=client_credentials" \--data-urlencode "client_id=$CLIENT_ID" \--data-urlencode "client_secret=$CLIENT_SECRET" | jq -r .access_token)# 2. Saldo (GET, corpo vazio)P="/v1/accounts/$ACCOUNT_ID/balance"sign GET "$P" "" ""curl -sS "$API_BASE$P" \-H "Authorization: Bearer $TOKEN" \-H "X-Tenant-Id: $TENANT_ID" \-H "X-Request-Timestamp: $TS" \-H "X-Content-SHA256: $SHA" \-H "X-Request-Signature: $SIG"echo# 3. Extrato (a query entra na assinatura exatamente como vai na URL)P="/v1/accounts/$ACCOUNT_ID/statement?startDate=2026-10-01&endDate=2026-10-15&order=asc&size=100"sign GET "$P" "" ""curl -sS "$API_BASE$P" \-H "Authorization: Bearer $TOKEN" \-H "X-Tenant-Id: $TENANT_ID" \-H "X-Request-Timestamp: $TS" \-H "X-Content-SHA256: $SHA" \-H "X-Request-Signature: $SIG"echo# 4. PIX por chave (POST: Idempotency-Key entra na assinatura)P="/v1/accounts/$ACCOUNT_ID/pix/out"BODY='{"amount":100.00,"keyType":"CPF","key":"12345678901","description":"Pedido 12345","identifier":"order-12345"}'IDEM=$(uuidgen | tr 'A-Z' 'a-z')sign POST "$P" "$BODY" "$IDEM"curl -sS -X POST "$API_BASE$P" \-H "Authorization: Bearer $TOKEN" \-H "X-Tenant-Id: $TENANT_ID" \-H "Idempotency-Key: $IDEM" \-H "Content-Type: application/json" \-H "X-Request-Timestamp: $TS" \-H "X-Content-SHA256: $SHA" \-H "X-Request-Signature: $SIG" \--data-binary "$BODY"echo
O openssl dgst -sign devolve ECDSA em DER. A função der_to_rs converte
para os 64 bytes R||S que o JWS exige; sem ela a API recusa a assinatura.
Node.js
Node 18 ou mais novo, sem dependências (fetch e crypto nativos).
// Node.js 18+: fetch e crypto nativos, sem dependências.import crypto from 'node:crypto';import { readFileSync } from 'node:fs';const TOKEN_URL = process.env.TOKEN_URL ?? 'https://auth.api.corpx.com/oauth2/token';const API_BASE = process.env.API_BASE ?? 'https://client.api.corpx.com';const { CLIENT_ID, CLIENT_SECRET, TENANT_ID, ACCOUNT_ID } = process.env;const privateKey = crypto.createPrivateKey(readFileSync(process.env.PRIVATE_KEY_FILE ?? './corpx-signing.key'));const ALG = privateKey.asymmetricKeyType === 'ec' ? 'ES256' : 'PS256';const spki = crypto.createPublicKey(privateKey).export({ type: 'spki', format: 'der' });const KID = crypto.createHash('sha256').update(spki).digest('hex').slice(0, 32);const b64url = (data) => Buffer.from(data).toString('base64url');const sha256Hex = (data) => crypto.createHash('sha256').update(data).digest('hex');function signatureHeaders(method, pathWithQuery, body = '', idempotencyKey = '') {const timestamp = String(Math.floor(Date.now() / 1000));const contentSha256 = sha256Hex(Buffer.from(body, 'utf8'));const canonical = [method.toUpperCase(), pathWithQuery, timestamp, idempotencyKey, contentSha256].join('\n');const protectedHeader = b64url(JSON.stringify({ alg: ALG, kid: KID, jti: crypto.randomUUID() }));const input = Buffer.from(`${protectedHeader}.${b64url(canonical)}`);const signature =ALG === 'ES256'? crypto.sign('sha256', input, { key: privateKey, dsaEncoding: 'ieee-p1363' }): crypto.sign('sha256', input, {key: privateKey,padding: crypto.constants.RSA_PKCS1_PSS_PADDING,saltLength: 32,});return {'X-Request-Timestamp': timestamp,'X-Content-SHA256': contentSha256,'X-Request-Signature': `${protectedHeader}..${b64url(signature)}`,};}let cachedToken = { value: '', expiresAt: 0 };async function getToken() {if (cachedToken.value && Date.now() < cachedToken.expiresAt - 60_000) return cachedToken.value;const res = await fetch(TOKEN_URL, {method: 'POST',headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: new URLSearchParams({grant_type: 'client_credentials',client_id: CLIENT_ID,client_secret: CLIENT_SECRET,}),});if (!res.ok) throw new Error(`token: HTTP ${res.status} ${await res.text()}`);const json = await res.json();cachedToken = { value: json.access_token, expiresAt: Date.now() + json.expires_in * 1000 };return cachedToken.value;}// Em retry de POST, reenvie a MESMA idempotencyKey.async function corpx(method, pathWithQuery, payload, idempotencyKey = '') {const body = payload === undefined ? '' : JSON.stringify(payload);const headers = {Authorization: `Bearer ${await getToken()}`,'X-Tenant-Id': TENANT_ID,...signatureHeaders(method, pathWithQuery, body, idempotencyKey),};if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;if (body) headers['Content-Type'] = 'application/json';const res = await fetch(API_BASE + pathWithQuery, { method, headers, body: body || undefined });const text = await res.text();if (!res.ok) throw new Error(`${method} ${pathWithQuery}: HTTP ${res.status} ${text}`);return text ? JSON.parse(text) : null;}const balance = await corpx('GET', `/v1/accounts/${ACCOUNT_ID}/balance`);console.log(balance);const statement = await corpx('GET',`/v1/accounts/${ACCOUNT_ID}/statement?startDate=2026-10-01&endDate=2026-10-15&order=asc&size=100`,);console.log(statement);const pix = await corpx('POST',`/v1/accounts/${ACCOUNT_ID}/pix/out`,{ amount: 100.0, keyType: 'CPF', key: '12345678901', description: 'Pedido 12345', identifier: 'order-12345' },crypto.randomUUID(),);console.log(pix);
Python
Python 3.9+ com cryptography e requests:
pip install cryptography requests
# Python 3.9+: pip install cryptography requestsimport base64import hashlibimport jsonimport osimport timeimport uuidimport requestsfrom cryptography.hazmat.primitives import hashes, serializationfrom cryptography.hazmat.primitives.asymmetric import ec, paddingfrom cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signatureTOKEN_URL = os.environ.get("TOKEN_URL", "https://auth.api.corpx.com/oauth2/token")API_BASE = os.environ.get("API_BASE", "https://client.api.corpx.com")CLIENT_ID = os.environ["CLIENT_ID"]CLIENT_SECRET = os.environ["CLIENT_SECRET"]TENANT_ID = os.environ["TENANT_ID"]ACCOUNT_ID = os.environ["ACCOUNT_ID"]with open(os.environ.get("PRIVATE_KEY_FILE", "corpx-signing.key"), "rb") as f:PRIVATE_KEY = serialization.load_pem_private_key(f.read(), password=None)ALG = "ES256" if isinstance(PRIVATE_KEY, ec.EllipticCurvePrivateKey) else "PS256"SPKI = PRIVATE_KEY.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)KID = hashlib.sha256(SPKI).hexdigest()[:32]def b64url(data: bytes) -> str:return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")def signature_headers(method: str, path_with_query: str, body: bytes = b"", idempotency_key: str = "") -> dict:timestamp = str(int(time.time()))content_sha256 = hashlib.sha256(body).hexdigest()canonical = "\n".join([method.upper(), path_with_query, timestamp, idempotency_key, content_sha256])header = {"alg": ALG, "kid": KID, "jti": str(uuid.uuid4())}protected = b64url(json.dumps(header, separators=(",", ":")).encode())signing_input = f"{protected}.{b64url(canonical.encode())}".encode("ascii")if ALG == "ES256":r, s = decode_dss_signature(PRIVATE_KEY.sign(signing_input, ec.ECDSA(hashes.SHA256())))signature = r.to_bytes(32, "big") + s.to_bytes(32, "big")else:signature = PRIVATE_KEY.sign(signing_input,padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32),hashes.SHA256(),)return {"X-Request-Timestamp": timestamp,"X-Content-SHA256": content_sha256,"X-Request-Signature": f"{protected}..{b64url(signature)}",}_token = {"value": "", "expires_at": 0.0}def get_token() -> str:if _token["value"] and time.time() < _token["expires_at"] - 60:return _token["value"]res = requests.post(TOKEN_URL,data={"grant_type": "client_credentials", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET},timeout=10,)res.raise_for_status()data = res.json()_token.update(value=data["access_token"], expires_at=time.time() + data["expires_in"])return _token["value"]def corpx(method: str, path_with_query: str, payload=None, idempotency_key: str = ""):"""Em retry de POST, reenvie a MESMA idempotency_key."""body = b"" if payload is None else json.dumps(payload, separators=(",", ":")).encode()headers = {"Authorization": f"Bearer {get_token()}","X-Tenant-Id": TENANT_ID,**signature_headers(method, path_with_query, body, idempotency_key),}if idempotency_key:headers["Idempotency-Key"] = idempotency_keyif body:headers["Content-Type"] = "application/json"res = requests.request(method, API_BASE + path_with_query, data=body or None, headers=headers, timeout=30)if not res.ok:raise RuntimeError(f"{method} {path_with_query}: HTTP {res.status_code} {res.text}")return res.json() if res.content else Noneif __name__ == "__main__":print(corpx("GET", f"/v1/accounts/{ACCOUNT_ID}/balance"))print(corpx("GET", f"/v1/accounts/{ACCOUNT_ID}/statement?startDate=2026-10-01&endDate=2026-10-15&order=asc&size=100"))print(corpx("POST",f"/v1/accounts/{ACCOUNT_ID}/pix/out",{"amount": 100.00, "keyType": "CPF", "key": "12345678901","description": "Pedido 12345", "identifier": "order-12345"},idempotency_key=str(uuid.uuid4()),))
cryptography devolve ECDSA em DER; decode_dss_signature extrai r e
s, que viram 32 bytes cada.
Go
Go 1.20+, só biblioteca padrão. Lê chave EC em PKCS#8
(openssl genpkey) ou SEC1 (openssl ecparam), e RSA em PKCS#8.
// Go 1.20+, só biblioteca padrão.package mainimport ("bytes""crypto""crypto/ecdsa""crypto/rand""crypto/rsa""crypto/sha256""crypto/x509""encoding/base64""encoding/hex""encoding/json""encoding/pem""fmt""io""net/http""net/url""os""strconv""strings""time")var (tokenURL = envOr("TOKEN_URL", "https://auth.api.corpx.com/oauth2/token")apiBase = envOr("API_BASE", "https://client.api.corpx.com")tenantID = os.Getenv("TENANT_ID")accountID = os.Getenv("ACCOUNT_ID"))type signer struct {key crypto.Signeralg stringkid string}func loadSigner(path string) (*signer, error) {raw, err := os.ReadFile(path)if err != nil {return nil, err}block, _ := pem.Decode(raw)if block == nil {return nil, fmt.Errorf("%s não é PEM", path)}var key anyif block.Type == "EC PRIVATE KEY" {key, err = x509.ParseECPrivateKey(block.Bytes)} else {key, err = x509.ParsePKCS8PrivateKey(block.Bytes)}if err != nil {return nil, err}s := &signer{key: key.(crypto.Signer)}switch key.(type) {case *ecdsa.PrivateKey:s.alg = "ES256"case *rsa.PrivateKey:s.alg = "PS256"default:return nil, fmt.Errorf("tipo de chave não suportado")}spki, err := x509.MarshalPKIXPublicKey(s.key.Public())if err != nil {return nil, err}sum := sha256.Sum256(spki)s.kid = hex.EncodeToString(sum[:16])return s, nil}func b64url(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }func (s *signer) headers(method, pathWithQuery string, body []byte, idempotencyKey string) (http.Header, error) {ts := strconv.FormatInt(time.Now().Unix(), 10)bodySum := sha256.Sum256(body)contentSHA := hex.EncodeToString(bodySum[:])canonical := strings.Join([]string{strings.ToUpper(method), pathWithQuery, ts, idempotencyKey, contentSHA}, "\n")hdr, _ := json.Marshal(map[string]string{"alg": s.alg, "kid": s.kid})protected := b64url(hdr)digest := sha256.Sum256([]byte(protected + "." + b64url([]byte(canonical))))var sig []byteswitch k := s.key.(type) {case *ecdsa.PrivateKey:r, ss, err := ecdsa.Sign(rand.Reader, k, digest[:])if err != nil {return nil, err}sig = make([]byte, 64) // R||S, 32 bytes cadar.FillBytes(sig[:32])ss.FillBytes(sig[32:])case *rsa.PrivateKey:var err errorsig, err = rsa.SignPSS(rand.Reader, k, crypto.SHA256, digest[:],&rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: crypto.SHA256})if err != nil {return nil, err}}h := http.Header{}h.Set("X-Request-Timestamp", ts)h.Set("X-Content-SHA256", contentSHA)h.Set("X-Request-Signature", protected+".."+b64url(sig))if idempotencyKey != "" {h.Set("Idempotency-Key", idempotencyKey)}return h, nil}func getToken() (string, error) {form := url.Values{"grant_type": {"client_credentials"},"client_id": {os.Getenv("CLIENT_ID")},"client_secret": {os.Getenv("CLIENT_SECRET")},}res, err := http.PostForm(tokenURL, form)if err != nil {return "", err}defer res.Body.Close()if res.StatusCode != http.StatusOK {b, _ := io.ReadAll(res.Body)return "", fmt.Errorf("token: HTTP %d %s", res.StatusCode, b)}var out struct {AccessToken string `json:"access_token"`ExpiresIn int `json:"expires_in"`}if err := json.NewDecoder(res.Body).Decode(&out); err != nil {return "", err}return out.AccessToken, nil}// Em retry de POST, reenvie a MESMA idempotencyKey.func (s *signer) call(token, method, pathWithQuery string, body []byte, idempotencyKey string) (string, error) {h, err := s.headers(method, pathWithQuery, body, idempotencyKey)if err != nil {return "", err}req, err := http.NewRequest(method, apiBase+pathWithQuery, bytes.NewReader(body))if err != nil {return "", err}req.Header = hreq.Header.Set("Authorization", "Bearer "+token)req.Header.Set("X-Tenant-Id", tenantID)if len(body) > 0 {req.Header.Set("Content-Type", "application/json")}res, err := http.DefaultClient.Do(req)if err != nil {return "", err}defer res.Body.Close()b, _ := io.ReadAll(res.Body)if res.StatusCode >= 300 {return "", fmt.Errorf("%s %s: HTTP %d %s", method, pathWithQuery, res.StatusCode, b)}return string(b), nil}func main() {s, err := loadSigner(envOr("PRIVATE_KEY_FILE", "corpx-signing.key"))check(err)token, err := getToken()check(err)out, err := s.call(token, "GET", "/v1/accounts/"+accountID+"/balance", nil, "")check(err)fmt.Println(out)out, err = s.call(token, "GET","/v1/accounts/"+accountID+"/statement?startDate=2026-10-01&endDate=2026-10-15&order=asc&size=100", nil, "")check(err)fmt.Println(out)body := []byte(`{"amount":100.00,"keyType":"CPF","key":"12345678901","description":"Pedido 12345","identifier":"order-12345"}`)out, err = s.call(token, "POST", "/v1/accounts/"+accountID+"/pix/out", body, newUUID())check(err)fmt.Println(out)}func newUUID() string {b := make([]byte, 16)_, _ = rand.Read(b)b[6] = b[6]&0x0f | 0x40b[8] = b[8]&0x3f | 0x80return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])}func envOr(k, def string) string {if v := os.Getenv(k); v != "" {return v}return def}func check(err error) {if err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(1)}}
Erros comuns
A recusa pode vir de dois lugares, e a resposta é diferente em cada um:
- Na borda (antes da aplicação):
401ou403com corpo{"message":"Unauthorized"}/{"message":"Forbidden"}, sem código. A borda não diz o motivo — percorra a lista abaixo. - Na aplicação: JSON com
errorCodedo catálogo de erros.
| Resposta | Causa provável | O que fazer |
|---|---|---|
401 Unauthorized (sem código) | Faltou Authorization, X-Request-Timestamp, X-Content-SHA256 ou X-Request-Signature | Envie os quatro em toda chamada, inclusive GET |
403 Forbidden (sem código) | Token inválido ou expirado | Peça outro token; renove quando faltar ~60s para expires_in |
403 Forbidden (sem código) | Relógio do servidor fora de ±300s, ou timestamp em milissegundos | Sincronize com NTP; use segundos (date +%s, Math.floor(Date.now()/1000)) |
403 Forbidden (sem código) | Assinatura não confere: string canônica diferente (CRLF, query faltando ou reordenada, Idempotency-Key diferente da enviada), ES256 em DER, kid errado | Compare com o vetor de teste e com canonicalString do autoteste |
403 Forbidden (sem código) | kid de chave ainda na carência de 18h, ou já aposentada | Assine com a chave antiga até a nova ficar ativa (rotação) |
403 Forbidden (sem código) | IP de saída fora da allowlist da credencial | Confira o IP público real (NAT, proxy, VPN) e cadastre-o; incluir IP também tem carência de 18h |
403 Forbidden (sem código) | Credencial em carência (activeFrom no futuro) ou revogada | Espere o activeFrom; se foi revogada, peça uma nova ao titular |
400 body_hash_mismatch | O corpo que chegou não é o que foi assinado: JSON reserializado, curl -d @arquivo (remove quebras de linha) em vez de --data-binary, middleware/proxy alterando o corpo | Hash e envio sobre a mesma string de bytes |
400 missing_tenant | Faltou X-Tenant-Id | Envie em toda chamada à conta |
403 tenant_forbidden / 403 tenant_mismatch | X-Tenant-Id de outro tenant, ou que não é o da conta no path | Use o identificador que o banco informou para esta conta |
403 forbidden | accountId no path diferente da conta da credencial | A credencial vale para uma única conta |
403 insufficient_scope | A rota exige um escopo que não foi marcado na emissão | Peça ao titular uma credencial com esse escopo |
403 signed_host_required | Credencial da conta usada em tenant.api.corpx.com | Use https://client.api.corpx.com |
400 invalid_client no token | client_id/client_secret errados, ou credencial revogada | Confira o segredo guardado na emissão; ele não é exibido de novo |
Rode o vetor de teste na sua implementação: com a mesma string canônica e a mesma chave, a sua função tem de produzir uma JWS que verifica contra a chave pública publicada. Se o vetor passa e a chamada real falha, o problema está nos dados (path, query, corpo, timestamp, IP), não na criptografia.