OAuth 2.0 / JWT authentication helpers for the Bling API v3
Project description
bling-jwt-auth-python
Repositório: github.com/tempont/bling-jwt-auth-python · PyPI: bling-jwt-auth
Biblioteca Python para autenticação OAuth 2.0 na API v3 do Bling, com suporte ao modo JWT exigido pelos endpoints atuais da plataforma.
Use este pacote quando sua aplicação precisa obter, persistir e renovar tokens do Bling sem reimplementar o fluxo OAuth. Ele cobre o caminho mais comum de integração:
- gerar a URL de autorização para o usuário conectar a conta Bling;
- trocar o
codedo callback poraccess_tokenerefresh_token; - salvar o token localmente em SQLite ou JSON;
- renovar automaticamente o
access_tokenantes da expiração; - montar os headers necessários para chamadas autenticadas à API v3.
Versão em inglês: docs/README.en.md
Requisitos
- Python 3.14 ou superior
- Uma aplicação OAuth cadastrada no Bling
client_id,client_secreteredirect_urida aplicação OAuth
Instalação
pip install bling-jwt-auth
Instalação direta do repositório:
pip install "git+https://github.com/tempont/bling-jwt-auth-python.git"
Para desenvolvimento local:
uv sync --extra dev
Configuração
Copie o arquivo de exemplo e preencha as credenciais da sua aplicação no Bling:
cp .env.example .env
BLING_CLIENT_ID=seu_client_id
BLING_CLIENT_SECRET=seu_client_secret
BLING_REDIRECT_URI=https://seu-dominio.com/oauth/callback
Por padrão, os tokens são salvos em SQLite em ~/.config/bling_jwt_auth/tokens.db.
Para salvar em um arquivo JSON:
BLING_TOKEN_STORE=file
BLING_TOKEN_STORE_PATH=./token.json
Para salvar SQLite em um caminho específico:
BLING_TOKEN_STORE=sqlite
BLING_TOKEN_STORE_PATH=./bling-tokens.db
Fluxo OAuth
1. Gere a URL de autorização
from bling_jwt_auth import BlingAuthSettings, OAuthClient
settings = BlingAuthSettings.load()
with OAuthClient(settings) as oauth:
url = oauth.build_authorization_url(state="valor-aleatorio-seguro")
print(url)
Abra a URL no navegador, autorize a aplicação no Bling e capture o parâmetro code recebido no callback configurado em BLING_REDIRECT_URI.
2. Troque o code por tokens e persista
from bling_jwt_auth import BlingAuthSettings, OAuthClient, TokenManager, create_token_store
settings = BlingAuthSettings.load()
store = create_token_store(settings)
with OAuthClient(settings) as oauth:
manager = TokenManager(oauth, store, settings)
manager.save_from_code("code-recebido-no-callback")
3. Use um access token valido
import httpx
from bling_jwt_auth import (
BlingAuthSettings,
OAuthClient,
TokenManager,
bling_api_headers,
create_token_store,
)
settings = BlingAuthSettings.load()
store = create_token_store(settings)
with OAuthClient(settings) as oauth:
manager = TokenManager(oauth, store, settings)
access_token = manager.get_access_token()
response = httpx.get(
"https://api.bling.com.br/Api/v3/produtos",
headers=bling_api_headers(access_token),
)
response.raise_for_status()
print(response.json())
TokenManager.get_access_token() lê o token salvo, verifica a expiração usando BLING_REFRESH_SKEW_SECONDS e faz refresh automaticamente quando necessário.
Exemplos executáveis
Fluxo manual de OAuth:
uv run python examples/oauth_flow.py
O script imprime a URL de autorização. Depois de autorizar no Bling, cole no terminal o code recebido no callback.
Para tentar abrir o navegador automaticamente:
uv run python examples/oauth_flow.py --open
Teste de chamada autenticada:
uv run python examples/authenticated_request.py
Esse exemplo usa o mesmo token salvo pelo fluxo OAuth, renova se necessário e chama o endpoint de homologação de produtos do Bling.
API principal
| Objeto | Uso |
|---|---|
BlingAuthSettings |
Carrega configuração a partir de variáveis BLING_* e .env. |
OAuthClient |
Cliente síncrono para autorização, troca de code, refresh e revogação. |
TokenManager |
Orquestra OAuthClient + TokenStore para salvar e renovar tokens. |
create_token_store |
Cria o backend de armazenamento configurado (sqlite ou file). |
SQLiteTokenStore |
Persiste um token em banco SQLite local. |
FileTokenStore |
Persiste um token em arquivo JSON local. |
bling_api_headers |
Monta Authorization: Bearer ... e enable-jwt: 1. |
Variáveis de ambiente
| Variável | Obrigatória | Padrão | Descrição |
|---|---|---|---|
BLING_CLIENT_ID |
Sim | - | Client ID da aplicação OAuth no Bling. |
BLING_CLIENT_SECRET |
Sim | - | Client secret da aplicação OAuth. |
BLING_REDIRECT_URI |
Sim | - | Callback cadastrado no Bling. |
BLING_ENABLE_JWT |
Não | true |
Envia o header enable-jwt: 1 nos endpoints OAuth. |
BLING_AUTHORIZE_URL |
Não | endpoint oficial | URL de autorização OAuth. |
BLING_TOKEN_URL |
Não | endpoint oficial | URL de troca e refresh de token. |
BLING_REVOKE_URL |
Não | endpoint oficial | URL de revogação de token. |
BLING_REFRESH_SKEW_SECONDS |
Não | 60 |
Margem, em segundos, para renovar antes da expiração real. |
BLING_TOKEN_STORE |
Não | sqlite |
Backend de token: sqlite ou file. |
BLING_TOKEN_STORE_PATH |
Não | ~/.config/... |
Caminho customizado para o banco ou JSON. |
Tratamento de erros
TokenNotFoundError: nenhum token foi salvo ainda. Execute o fluxo OAuth ou chameTokenManager.save_from_code().OAuthRequestError: o Bling retornou erro HTTP em troca, refresh ou revogação. A exceção preservastatus_codeeresponse_body.ValueError: argumentos obrigatórios vazios, comostate,codeourefresh_token.
Segurança
- Não versione
.env,token.jsonou bancos SQLite com tokens. - Use um
statealeatório e valide-o no callback OAuth da sua aplicação. - Configure
BLING_REDIRECT_URIexatamente igual ao callback cadastrado no Bling. - Em produção, prefira guardar credenciais em variáveis de ambiente ou secret manager.
- O backend JSON aplica permissão
0600em sistemas POSIX depois da escrita.
Desenvolvimento
Rodar lint, checagem de tipos e testes:
make check
Ou:
bash scripts/check.sh
Rodar apenas testes:
uv run --extra dev pytest
Gerar artefatos de distribuição local:
uv run --extra dev python -m build
uv run --extra dev python -m twine check dist/*
Licença
MIT. Veja LICENSE.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file bling_jwt_auth-0.1.1.tar.gz.
File metadata
- Download URL: bling_jwt_auth-0.1.1.tar.gz
- Upload date:
- Size: 20.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
678269b15df144786b483061633a4b3cbbd2ae8a5a2c94aba17fd7227b55f9e8
|
|
| MD5 |
b4428f2ecfd4a0e9677609b738bd98e1
|
|
| BLAKE2b-256 |
a9d32d88fed3a0bc9d3b7fe09a6283240fb19c551f96a82e7466c620fe3dfc39
|
Provenance
The following attestation bundles were made for bling_jwt_auth-0.1.1.tar.gz:
Publisher:
publish.yml on tempont/bling-jwt-auth-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
bling_jwt_auth-0.1.1.tar.gz -
Subject digest:
678269b15df144786b483061633a4b3cbbd2ae8a5a2c94aba17fd7227b55f9e8 - Sigstore transparency entry: 1570623144
- Sigstore integration time:
-
Permalink:
tempont/bling-jwt-auth-python@15d176ae7af282ddcd567fcc8b03cf39b2a82909 -
Branch / Tag:
refs/tags/v0.1.1 - Owner: https://github.com/tempont
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@15d176ae7af282ddcd567fcc8b03cf39b2a82909 -
Trigger Event:
release
-
Statement type:
File details
Details for the file bling_jwt_auth-0.1.1-py3-none-any.whl.
File metadata
- Download URL: bling_jwt_auth-0.1.1-py3-none-any.whl
- Upload date:
- Size: 17.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
80ca53dcae711e10db21d2a761eb9205dfa0a6b1ed22bfe93f953dafb1200b06
|
|
| MD5 |
0e136afc04537de041be65338edc3643
|
|
| BLAKE2b-256 |
5990bc308f887d8ca19f05822e07c8d235e1c57871ec282318dc683e1d48485a
|
Provenance
The following attestation bundles were made for bling_jwt_auth-0.1.1-py3-none-any.whl:
Publisher:
publish.yml on tempont/bling-jwt-auth-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
bling_jwt_auth-0.1.1-py3-none-any.whl -
Subject digest:
80ca53dcae711e10db21d2a761eb9205dfa0a6b1ed22bfe93f953dafb1200b06 - Sigstore transparency entry: 1570623448
- Sigstore integration time:
-
Permalink:
tempont/bling-jwt-auth-python@15d176ae7af282ddcd567fcc8b03cf39b2a82909 -
Branch / Tag:
refs/tags/v0.1.1 - Owner: https://github.com/tempont
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@15d176ae7af282ddcd567fcc8b03cf39b2a82909 -
Trigger Event:
release
-
Statement type: